JHong
commited on
Commit
•
a45bc4e
1
Parent(s):
4ef772d
Add application file
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +31 -0
- README.md +6 -10
- app.py +615 -0
- data/prompts/complex_reasoning/000_caps.txt +18 -0
- data/prompts/complex_reasoning/000_conv.txt +5 -0
- data/prompts/complex_reasoning/001_caps.txt +18 -0
- data/prompts/complex_reasoning/001_conv.txt +5 -0
- data/prompts/complex_reasoning/002_caps.txt +7 -0
- data/prompts/complex_reasoning/002_conv.txt +5 -0
- data/prompts/complex_reasoning/system_message.txt +10 -0
- data/prompts/conversation/000_caps.txt +5 -0
- data/prompts/conversation/000_conv.txt +29 -0
- data/prompts/conversation/001_caps.txt +5 -0
- data/prompts/conversation/001_conv.txt +37 -0
- data/prompts/conversation/system_message.txt +12 -0
- data/prompts/detail_description/000_caps.txt +18 -0
- data/prompts/detail_description/000_conv.txt +3 -0
- data/prompts/detail_description/001_caps.txt +18 -0
- data/prompts/detail_description/001_conv.txt +5 -0
- data/prompts/detail_description/002_caps.txt +15 -0
- data/prompts/detail_description/002_conv.txt +3 -0
- data/prompts/detail_description/system_message.txt +7 -0
- llava/__init__.py +1 -0
- llava/constants.py +12 -0
- llava/conversation.py +381 -0
- llava/eval/eval_gpt_review.py +113 -0
- llava/eval/eval_gpt_review_bench.py +121 -0
- llava/eval/eval_gpt_review_visual.py +118 -0
- llava/eval/eval_pope.py +81 -0
- llava/eval/eval_science_qa.py +99 -0
- llava/eval/eval_science_qa_gpt4.py +104 -0
- llava/eval/eval_science_qa_gpt4_requery.py +149 -0
- llava/eval/eval_textvqa.py +65 -0
- llava/eval/generate_webpage_data_from_table.py +111 -0
- llava/eval/m4c_evaluator.py +334 -0
- llava/eval/model_captioning.py +145 -0
- llava/eval/model_qa.py +85 -0
- llava/eval/model_vqa.py +112 -0
- llava/eval/model_vqa_loader.py +145 -0
- llava/eval/model_vqa_mmbench.py +170 -0
- llava/eval/model_vqa_qbench.py +122 -0
- llava/eval/model_vqa_science.py +141 -0
- llava/eval/qa_baseline_gpt35.py +74 -0
- llava/eval/run_llava.py +97 -0
- llava/eval/summarize_gpt_review.py +50 -0
- llava/eval/webpage/figures/alpaca.png +0 -0
- llava/eval/webpage/figures/bard.jpg +0 -0
- llava/eval/webpage/figures/chatgpt.svg +1 -0
- llava/eval/webpage/figures/llama.jpg +0 -0
- llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg +1 -0
.gitignore
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Python
|
2 |
+
__pycache__
|
3 |
+
*.pyc
|
4 |
+
*.egg-info
|
5 |
+
dist
|
6 |
+
|
7 |
+
# Log
|
8 |
+
*.log
|
9 |
+
*.log.*
|
10 |
+
*.json
|
11 |
+
*.jsonl
|
12 |
+
|
13 |
+
# Data
|
14 |
+
!**/alpaca-data-conversation.json
|
15 |
+
|
16 |
+
# Editor
|
17 |
+
.idea
|
18 |
+
*.swp
|
19 |
+
|
20 |
+
# Other
|
21 |
+
.DS_Store
|
22 |
+
wandb
|
23 |
+
output
|
24 |
+
|
25 |
+
checkpoints
|
26 |
+
ckpts*
|
27 |
+
|
28 |
+
.ipynb_checkpoints
|
29 |
+
*.ipynb
|
30 |
+
|
31 |
+
*.log
|
README.md
CHANGED
@@ -1,13 +1,9 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
colorTo: gray
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
-
|
9 |
-
|
10 |
-
license: apache-2.0
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: LLaVA
|
3 |
+
emoji: 🔥
|
4 |
+
colorFrom: purple
|
5 |
colorTo: gray
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.36.1
|
8 |
+
app_port: 7860
|
9 |
+
---
|
|
|
|
|
|
|
|
app.py
ADDED
@@ -0,0 +1,615 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import datetime
|
3 |
+
import hashlib
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import subprocess
|
7 |
+
import sys
|
8 |
+
import time
|
9 |
+
|
10 |
+
import gradio as gr
|
11 |
+
import requests
|
12 |
+
|
13 |
+
from llava.constants import LOGDIR
|
14 |
+
from llava.conversation import SeparatorStyle, conv_templates, default_conversation
|
15 |
+
from llava.utils import (
|
16 |
+
build_logger,
|
17 |
+
moderation_msg,
|
18 |
+
server_error_msg,
|
19 |
+
violates_moderation,
|
20 |
+
)
|
21 |
+
|
22 |
+
logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
23 |
+
|
24 |
+
headers = {"User-Agent": "LLaVA Client"}
|
25 |
+
|
26 |
+
no_change_btn = gr.Button.update()
|
27 |
+
enable_btn = gr.Button.update(interactive=True)
|
28 |
+
disable_btn = gr.Button.update(interactive=False)
|
29 |
+
|
30 |
+
priority = {
|
31 |
+
"vicuna-13b": "aaaaaaa",
|
32 |
+
"koala-13b": "aaaaaab",
|
33 |
+
}
|
34 |
+
|
35 |
+
|
36 |
+
def get_conv_log_filename():
|
37 |
+
t = datetime.datetime.now()
|
38 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
39 |
+
return name
|
40 |
+
|
41 |
+
|
42 |
+
def get_model_list():
|
43 |
+
ret = requests.post(args.controller_url + "/refresh_all_workers")
|
44 |
+
assert ret.status_code == 200
|
45 |
+
ret = requests.post(args.controller_url + "/list_models")
|
46 |
+
models = ret.json()["models"]
|
47 |
+
models.sort(key=lambda x: priority.get(x, x))
|
48 |
+
logger.info(f"Models: {models}")
|
49 |
+
return models
|
50 |
+
|
51 |
+
|
52 |
+
get_window_url_params = """
|
53 |
+
function() {
|
54 |
+
const params = new URLSearchParams(window.location.search);
|
55 |
+
url_params = Object.fromEntries(params);
|
56 |
+
console.log(url_params);
|
57 |
+
return url_params;
|
58 |
+
}
|
59 |
+
"""
|
60 |
+
|
61 |
+
|
62 |
+
def load_demo(url_params, request: gr.Request):
|
63 |
+
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
64 |
+
|
65 |
+
dropdown_update = gr.Dropdown.update(visible=True)
|
66 |
+
if "model" in url_params:
|
67 |
+
model = url_params["model"]
|
68 |
+
if model in models:
|
69 |
+
dropdown_update = gr.Dropdown.update(value=model, visible=True)
|
70 |
+
|
71 |
+
state = default_conversation.copy()
|
72 |
+
return state, dropdown_update
|
73 |
+
|
74 |
+
|
75 |
+
def load_demo_refresh_model_list(request: gr.Request):
|
76 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
77 |
+
models = get_model_list()
|
78 |
+
state = default_conversation.copy()
|
79 |
+
|
80 |
+
models_downloaded = True if models else False
|
81 |
+
|
82 |
+
model_dropdown_kwargs = {
|
83 |
+
"choices": [],
|
84 |
+
"value": "Downloading the models...",
|
85 |
+
"interactive": models_downloaded,
|
86 |
+
}
|
87 |
+
|
88 |
+
if models_downloaded:
|
89 |
+
model_dropdown_kwargs["choices"] = models
|
90 |
+
model_dropdown_kwargs["value"] = models[0]
|
91 |
+
|
92 |
+
models_dropdown_update = gr.Dropdown.update(**model_dropdown_kwargs)
|
93 |
+
|
94 |
+
send_button_update = gr.Button.update(
|
95 |
+
interactive=models_downloaded,
|
96 |
+
)
|
97 |
+
|
98 |
+
return state, models_dropdown_update, send_button_update
|
99 |
+
|
100 |
+
|
101 |
+
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
|
102 |
+
with open(get_conv_log_filename(), "a") as fout:
|
103 |
+
data = {
|
104 |
+
"tstamp": round(time.time(), 4),
|
105 |
+
"type": vote_type,
|
106 |
+
"model": model_selector,
|
107 |
+
"state": state.dict(),
|
108 |
+
"ip": request.client.host,
|
109 |
+
}
|
110 |
+
fout.write(json.dumps(data) + "\n")
|
111 |
+
|
112 |
+
|
113 |
+
def upvote_last_response(state, model_selector, request: gr.Request):
|
114 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
115 |
+
vote_last_response(state, "upvote", model_selector, request)
|
116 |
+
return ("",) + (disable_btn,) * 3
|
117 |
+
|
118 |
+
|
119 |
+
def downvote_last_response(state, model_selector, request: gr.Request):
|
120 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
121 |
+
vote_last_response(state, "downvote", model_selector, request)
|
122 |
+
return ("",) + (disable_btn,) * 3
|
123 |
+
|
124 |
+
|
125 |
+
def flag_last_response(state, model_selector, request: gr.Request):
|
126 |
+
logger.info(f"flag. ip: {request.client.host}")
|
127 |
+
vote_last_response(state, "flag", model_selector, request)
|
128 |
+
return ("",) + (disable_btn,) * 3
|
129 |
+
|
130 |
+
|
131 |
+
def regenerate(state, image_process_mode, request: gr.Request):
|
132 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
133 |
+
state.messages[-1][-1] = None
|
134 |
+
prev_human_msg = state.messages[-2]
|
135 |
+
if type(prev_human_msg[1]) in (tuple, list):
|
136 |
+
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
137 |
+
state.skip_next = False
|
138 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
139 |
+
|
140 |
+
|
141 |
+
def clear_history(request: gr.Request):
|
142 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
143 |
+
state = default_conversation.copy()
|
144 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
145 |
+
|
146 |
+
|
147 |
+
def add_text(state, text, image, image_process_mode, request: gr.Request):
|
148 |
+
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
149 |
+
if len(text) <= 0 and image is None:
|
150 |
+
state.skip_next = True
|
151 |
+
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
152 |
+
if args.moderate:
|
153 |
+
flagged = violates_moderation(text)
|
154 |
+
if flagged:
|
155 |
+
state.skip_next = True
|
156 |
+
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
|
157 |
+
no_change_btn,
|
158 |
+
) * 5
|
159 |
+
|
160 |
+
text = text[:1536] # Hard cut-off
|
161 |
+
if image is not None:
|
162 |
+
text = text[:1200] # Hard cut-off for images
|
163 |
+
if "<image>" not in text:
|
164 |
+
# text = '<Image><image></Image>' + text
|
165 |
+
text = text + "\n<image>"
|
166 |
+
text = (text, image, image_process_mode)
|
167 |
+
if len(state.get_images(return_pil=True)) > 0:
|
168 |
+
state = default_conversation.copy()
|
169 |
+
state.append_message(state.roles[0], text)
|
170 |
+
state.append_message(state.roles[1], None)
|
171 |
+
state.skip_next = False
|
172 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
173 |
+
|
174 |
+
|
175 |
+
def http_bot(
|
176 |
+
state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request
|
177 |
+
):
|
178 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
179 |
+
start_tstamp = time.time()
|
180 |
+
model_name = model_selector
|
181 |
+
|
182 |
+
if state.skip_next:
|
183 |
+
# This generate call is skipped due to invalid inputs
|
184 |
+
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
185 |
+
return
|
186 |
+
|
187 |
+
if len(state.messages) == state.offset + 2:
|
188 |
+
# First round of conversation
|
189 |
+
if "llava" in model_name.lower():
|
190 |
+
if "llama-2" in model_name.lower():
|
191 |
+
template_name = "llava_llama_2"
|
192 |
+
elif "v1" in model_name.lower():
|
193 |
+
if "mmtag" in model_name.lower():
|
194 |
+
template_name = "v1_mmtag"
|
195 |
+
elif (
|
196 |
+
"plain" in model_name.lower()
|
197 |
+
and "finetune" not in model_name.lower()
|
198 |
+
):
|
199 |
+
template_name = "v1_mmtag"
|
200 |
+
else:
|
201 |
+
template_name = "llava_v1"
|
202 |
+
elif "mpt" in model_name.lower():
|
203 |
+
template_name = "mpt"
|
204 |
+
else:
|
205 |
+
if "mmtag" in model_name.lower():
|
206 |
+
template_name = "v0_mmtag"
|
207 |
+
elif (
|
208 |
+
"plain" in model_name.lower()
|
209 |
+
and "finetune" not in model_name.lower()
|
210 |
+
):
|
211 |
+
template_name = "v0_mmtag"
|
212 |
+
else:
|
213 |
+
template_name = "llava_v0"
|
214 |
+
elif "mpt" in model_name:
|
215 |
+
template_name = "mpt_text"
|
216 |
+
elif "llama-2" in model_name:
|
217 |
+
template_name = "llama_2"
|
218 |
+
else:
|
219 |
+
template_name = "vicuna_v1"
|
220 |
+
new_state = conv_templates[template_name].copy()
|
221 |
+
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
222 |
+
new_state.append_message(new_state.roles[1], None)
|
223 |
+
state = new_state
|
224 |
+
|
225 |
+
# Query worker address
|
226 |
+
controller_url = args.controller_url
|
227 |
+
ret = requests.post(
|
228 |
+
controller_url + "/get_worker_address", json={"model": model_name}
|
229 |
+
)
|
230 |
+
worker_addr = ret.json()["address"]
|
231 |
+
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
|
232 |
+
|
233 |
+
# No available worker
|
234 |
+
if worker_addr == "":
|
235 |
+
state.messages[-1][-1] = server_error_msg
|
236 |
+
yield (
|
237 |
+
state,
|
238 |
+
state.to_gradio_chatbot(),
|
239 |
+
disable_btn,
|
240 |
+
disable_btn,
|
241 |
+
disable_btn,
|
242 |
+
enable_btn,
|
243 |
+
enable_btn,
|
244 |
+
)
|
245 |
+
return
|
246 |
+
|
247 |
+
# Construct prompt
|
248 |
+
prompt = state.get_prompt()
|
249 |
+
|
250 |
+
all_images = state.get_images(return_pil=True)
|
251 |
+
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
252 |
+
for image, hash in zip(all_images, all_image_hash):
|
253 |
+
t = datetime.datetime.now()
|
254 |
+
filename = os.path.join(
|
255 |
+
LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg"
|
256 |
+
)
|
257 |
+
if not os.path.isfile(filename):
|
258 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
259 |
+
image.save(filename)
|
260 |
+
|
261 |
+
# Make requests
|
262 |
+
pload = {
|
263 |
+
"model": model_name,
|
264 |
+
"prompt": prompt,
|
265 |
+
"temperature": float(temperature),
|
266 |
+
"top_p": float(top_p),
|
267 |
+
"max_new_tokens": min(int(max_new_tokens), 1536),
|
268 |
+
"stop": state.sep
|
269 |
+
if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT]
|
270 |
+
else state.sep2,
|
271 |
+
"images": f"List of {len(state.get_images())} images: {all_image_hash}",
|
272 |
+
}
|
273 |
+
logger.info(f"==== request ====\n{pload}")
|
274 |
+
|
275 |
+
pload["images"] = state.get_images()
|
276 |
+
|
277 |
+
state.messages[-1][-1] = "▌"
|
278 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
279 |
+
|
280 |
+
try:
|
281 |
+
# Stream output
|
282 |
+
response = requests.post(
|
283 |
+
worker_addr + "/worker_generate_stream",
|
284 |
+
headers=headers,
|
285 |
+
json=pload,
|
286 |
+
stream=True,
|
287 |
+
timeout=10,
|
288 |
+
)
|
289 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
290 |
+
if chunk:
|
291 |
+
data = json.loads(chunk.decode())
|
292 |
+
if data["error_code"] == 0:
|
293 |
+
output = data["text"][len(prompt) :].strip()
|
294 |
+
state.messages[-1][-1] = output + "▌"
|
295 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
296 |
+
else:
|
297 |
+
output = data["text"] + f" (error_code: {data['error_code']})"
|
298 |
+
state.messages[-1][-1] = output
|
299 |
+
yield (state, state.to_gradio_chatbot()) + (
|
300 |
+
disable_btn,
|
301 |
+
disable_btn,
|
302 |
+
disable_btn,
|
303 |
+
enable_btn,
|
304 |
+
enable_btn,
|
305 |
+
)
|
306 |
+
return
|
307 |
+
time.sleep(0.03)
|
308 |
+
except requests.exceptions.RequestException as e:
|
309 |
+
state.messages[-1][-1] = server_error_msg
|
310 |
+
yield (state, state.to_gradio_chatbot()) + (
|
311 |
+
disable_btn,
|
312 |
+
disable_btn,
|
313 |
+
disable_btn,
|
314 |
+
enable_btn,
|
315 |
+
enable_btn,
|
316 |
+
)
|
317 |
+
return
|
318 |
+
|
319 |
+
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
320 |
+
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
321 |
+
|
322 |
+
finish_tstamp = time.time()
|
323 |
+
logger.info(f"{output}")
|
324 |
+
|
325 |
+
with open(get_conv_log_filename(), "a") as fout:
|
326 |
+
data = {
|
327 |
+
"tstamp": round(finish_tstamp, 4),
|
328 |
+
"type": "chat",
|
329 |
+
"model": model_name,
|
330 |
+
"start": round(start_tstamp, 4),
|
331 |
+
"finish": round(start_tstamp, 4),
|
332 |
+
"state": state.dict(),
|
333 |
+
"images": all_image_hash,
|
334 |
+
"ip": request.client.host,
|
335 |
+
}
|
336 |
+
fout.write(json.dumps(data) + "\n")
|
337 |
+
|
338 |
+
|
339 |
+
title_markdown = """
|
340 |
+
# CXR-LLaVA: Chest X-Ray Large Language and Vision Assistant - Online Demo
|
341 |
+
🥰 This project is based on the codebase of [LLaVA](https://llava-vl.github.io/) by Haotian Liu et al. Many thanks to them! As CXR-LLaVA is temporarily not released as a paper, please [cite their work](https://github.com/haotian-liu/LLaVA/tree/main#citation) if you are further developing on CXR-LLaVA.
|
342 |
+
"""
|
343 |
+
|
344 |
+
tos_markdown = """
|
345 |
+
### Terms of use
|
346 |
+
By using this service, users are required to agree to the following terms:
|
347 |
+
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
|
348 |
+
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
349 |
+
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
350 |
+
"""
|
351 |
+
|
352 |
+
|
353 |
+
learn_more_markdown = """
|
354 |
+
### License
|
355 |
+
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
|
356 |
+
"""
|
357 |
+
|
358 |
+
block_css = """
|
359 |
+
|
360 |
+
#buttons button {
|
361 |
+
min-width: min(120px,100%);
|
362 |
+
}
|
363 |
+
|
364 |
+
"""
|
365 |
+
|
366 |
+
|
367 |
+
def build_demo(embed_mode):
|
368 |
+
models = get_model_list()
|
369 |
+
|
370 |
+
textbox = gr.Textbox(
|
371 |
+
show_label=False, placeholder="Enter text and press ENTER", container=False
|
372 |
+
)
|
373 |
+
with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
|
374 |
+
state = gr.State(default_conversation.copy())
|
375 |
+
|
376 |
+
if not embed_mode:
|
377 |
+
gr.Markdown(title_markdown)
|
378 |
+
|
379 |
+
with gr.Row():
|
380 |
+
with gr.Column(scale=3):
|
381 |
+
with gr.Row(elem_id="model_selector_row"):
|
382 |
+
model_selector = gr.Dropdown(
|
383 |
+
choices=models,
|
384 |
+
value=models[0] if models else "Downloading the models...",
|
385 |
+
interactive=True if models else False,
|
386 |
+
show_label=False,
|
387 |
+
container=False,
|
388 |
+
)
|
389 |
+
|
390 |
+
imagebox = gr.Image(type="pil")
|
391 |
+
image_process_mode = gr.Radio(
|
392 |
+
["Crop", "Resize", "Pad", "Default"],
|
393 |
+
value="Default",
|
394 |
+
label="Preprocess for non-square image",
|
395 |
+
visible=False,
|
396 |
+
)
|
397 |
+
|
398 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
399 |
+
gr.Examples(
|
400 |
+
examples=[
|
401 |
+
[
|
402 |
+
f"{cur_dir}/examples/extreme_ironing.jpg",
|
403 |
+
"What is unusual about this image?",
|
404 |
+
],
|
405 |
+
[
|
406 |
+
f"{cur_dir}/examples/waterview.jpg",
|
407 |
+
"What are the things I should be cautious about when I visit here?",
|
408 |
+
],
|
409 |
+
],
|
410 |
+
inputs=[imagebox, textbox],
|
411 |
+
)
|
412 |
+
|
413 |
+
with gr.Accordion("Parameters", open=False) as parameter_row:
|
414 |
+
temperature = gr.Slider(
|
415 |
+
minimum=0.0,
|
416 |
+
maximum=1.0,
|
417 |
+
value=0.2,
|
418 |
+
step=0.1,
|
419 |
+
interactive=True,
|
420 |
+
label="Temperature",
|
421 |
+
)
|
422 |
+
top_p = gr.Slider(
|
423 |
+
minimum=0.0,
|
424 |
+
maximum=1.0,
|
425 |
+
value=0.7,
|
426 |
+
step=0.1,
|
427 |
+
interactive=True,
|
428 |
+
label="Top P",
|
429 |
+
)
|
430 |
+
max_output_tokens = gr.Slider(
|
431 |
+
minimum=0,
|
432 |
+
maximum=1024,
|
433 |
+
value=512,
|
434 |
+
step=64,
|
435 |
+
interactive=True,
|
436 |
+
label="Max output tokens",
|
437 |
+
)
|
438 |
+
|
439 |
+
with gr.Column(scale=8):
|
440 |
+
chatbot = gr.Chatbot(
|
441 |
+
elem_id="chatbot", label="LLaVA Chatbot", height=550
|
442 |
+
)
|
443 |
+
with gr.Row():
|
444 |
+
with gr.Column(scale=8):
|
445 |
+
textbox.render()
|
446 |
+
with gr.Column(scale=1, min_width=50):
|
447 |
+
submit_btn = gr.Button(
|
448 |
+
value="Send", variant="primary", interactive=False
|
449 |
+
)
|
450 |
+
with gr.Row(elem_id="buttons") as button_row:
|
451 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
452 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
453 |
+
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
454 |
+
# stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
455 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
456 |
+
clear_btn = gr.Button(value="🗑️ Clear history", interactive=False)
|
457 |
+
|
458 |
+
if not embed_mode:
|
459 |
+
gr.Markdown(tos_markdown)
|
460 |
+
gr.Markdown(learn_more_markdown)
|
461 |
+
url_params = gr.JSON(visible=False)
|
462 |
+
|
463 |
+
# Register listeners
|
464 |
+
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
465 |
+
upvote_btn.click(
|
466 |
+
upvote_last_response,
|
467 |
+
[state, model_selector],
|
468 |
+
[textbox, upvote_btn, downvote_btn, flag_btn],
|
469 |
+
)
|
470 |
+
downvote_btn.click(
|
471 |
+
downvote_last_response,
|
472 |
+
[state, model_selector],
|
473 |
+
[textbox, upvote_btn, downvote_btn, flag_btn],
|
474 |
+
)
|
475 |
+
flag_btn.click(
|
476 |
+
flag_last_response,
|
477 |
+
[state, model_selector],
|
478 |
+
[textbox, upvote_btn, downvote_btn, flag_btn],
|
479 |
+
)
|
480 |
+
regenerate_btn.click(
|
481 |
+
regenerate,
|
482 |
+
[state, image_process_mode],
|
483 |
+
[state, chatbot, textbox, imagebox] + btn_list,
|
484 |
+
).then(
|
485 |
+
http_bot,
|
486 |
+
[state, model_selector, temperature, top_p, max_output_tokens],
|
487 |
+
[state, chatbot] + btn_list,
|
488 |
+
)
|
489 |
+
clear_btn.click(
|
490 |
+
clear_history, None, [state, chatbot, textbox, imagebox] + btn_list
|
491 |
+
)
|
492 |
+
|
493 |
+
textbox.submit(
|
494 |
+
add_text,
|
495 |
+
[state, textbox, imagebox, image_process_mode],
|
496 |
+
[state, chatbot, textbox, imagebox] + btn_list,
|
497 |
+
).then(
|
498 |
+
http_bot,
|
499 |
+
[state, model_selector, temperature, top_p, max_output_tokens],
|
500 |
+
[state, chatbot] + btn_list,
|
501 |
+
)
|
502 |
+
submit_btn.click(
|
503 |
+
add_text,
|
504 |
+
[state, textbox, imagebox, image_process_mode],
|
505 |
+
[state, chatbot, textbox, imagebox] + btn_list,
|
506 |
+
).then(
|
507 |
+
http_bot,
|
508 |
+
[state, model_selector, temperature, top_p, max_output_tokens],
|
509 |
+
[state, chatbot] + btn_list,
|
510 |
+
)
|
511 |
+
|
512 |
+
if args.model_list_mode == "once":
|
513 |
+
demo.load(
|
514 |
+
load_demo,
|
515 |
+
[url_params],
|
516 |
+
[state, model_selector],
|
517 |
+
_js=get_window_url_params,
|
518 |
+
)
|
519 |
+
elif args.model_list_mode == "reload":
|
520 |
+
demo.load(
|
521 |
+
load_demo_refresh_model_list, None, [state, model_selector, submit_btn]
|
522 |
+
)
|
523 |
+
else:
|
524 |
+
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
|
525 |
+
|
526 |
+
return demo
|
527 |
+
|
528 |
+
|
529 |
+
def start_controller():
|
530 |
+
logger.info("Starting the controller")
|
531 |
+
controller_command = [
|
532 |
+
"python",
|
533 |
+
"-m",
|
534 |
+
"llava.serve.controller",
|
535 |
+
"--host",
|
536 |
+
"0.0.0.0",
|
537 |
+
"--port",
|
538 |
+
"10000",
|
539 |
+
]
|
540 |
+
return subprocess.Popen(controller_command)
|
541 |
+
|
542 |
+
|
543 |
+
def start_worker(model_path: str, bits=16):
|
544 |
+
logger.info(f"Starting the model worker for the model {model_path}")
|
545 |
+
model_name = model_path.strip("/").split("/")[-1]
|
546 |
+
assert bits in [4, 8, 16], "It can be only loaded with 16-bit, 8-bit, and 4-bit."
|
547 |
+
if bits != 16:
|
548 |
+
model_name += f"-{bits}bit"
|
549 |
+
worker_command = [
|
550 |
+
"python",
|
551 |
+
"-m",
|
552 |
+
"llava.serve.model_worker",
|
553 |
+
"--host",
|
554 |
+
"0.0.0.0",
|
555 |
+
"--controller",
|
556 |
+
"http://localhost:10000",
|
557 |
+
"--model-path",
|
558 |
+
model_path,
|
559 |
+
"--model-name",
|
560 |
+
model_name,
|
561 |
+
]
|
562 |
+
if bits != 16:
|
563 |
+
worker_command += [f"--load-{bits}bit"]
|
564 |
+
return subprocess.Popen(worker_command)
|
565 |
+
|
566 |
+
|
567 |
+
def get_args():
|
568 |
+
parser = argparse.ArgumentParser()
|
569 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
570 |
+
parser.add_argument("--port", type=int)
|
571 |
+
parser.add_argument("--controller-url", type=str, default="http://localhost:10000")
|
572 |
+
parser.add_argument("--concurrency-count", type=int, default=8)
|
573 |
+
parser.add_argument(
|
574 |
+
"--model-list-mode", type=str, default="reload", choices=["once", "reload"]
|
575 |
+
)
|
576 |
+
parser.add_argument("--share", action="store_true")
|
577 |
+
parser.add_argument("--moderate", action="store_true")
|
578 |
+
parser.add_argument("--embed", action="store_true")
|
579 |
+
|
580 |
+
args = parser.parse_args()
|
581 |
+
|
582 |
+
return args
|
583 |
+
|
584 |
+
|
585 |
+
def start_demo(args):
|
586 |
+
demo = build_demo(args.embed)
|
587 |
+
demo.queue(
|
588 |
+
concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False
|
589 |
+
).launch(server_name=args.host, server_port=args.port, share=args.share)
|
590 |
+
|
591 |
+
|
592 |
+
if __name__ == "__main__":
|
593 |
+
args = get_args()
|
594 |
+
logger.info(f"args: {args}")
|
595 |
+
|
596 |
+
model_path = "models/TommyIX/CXR-LLaVA-7b"
|
597 |
+
bits = int(os.getenv("bits", 8))
|
598 |
+
|
599 |
+
controller_proc = start_controller()
|
600 |
+
worker_proc = start_worker(model_path, bits=bits)
|
601 |
+
|
602 |
+
# Wait for worker and controller to start
|
603 |
+
time.sleep(10)
|
604 |
+
|
605 |
+
exit_status = 0
|
606 |
+
try:
|
607 |
+
start_demo(args)
|
608 |
+
except Exception as e:
|
609 |
+
print(e)
|
610 |
+
exit_status = 1
|
611 |
+
finally:
|
612 |
+
worker_proc.kill()
|
613 |
+
controller_proc.kill()
|
614 |
+
|
615 |
+
sys.exit(exit_status)
|
data/prompts/complex_reasoning/000_caps.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A man wearing multiple neck ties making a goofy face.
|
2 |
+
A man in a white shirt wearing very many ties.
|
3 |
+
a man with ties on poses for a picture
|
4 |
+
A man wearing multiple ties on his neck.
|
5 |
+
A young man smiles while wearing several ties.
|
6 |
+
|
7 |
+
tie: [0.574, 0.298, 0.752, 0.704]
|
8 |
+
tie: [0.464, 0.339, 0.639, 0.789]
|
9 |
+
tie: [0.349, 0.363, 0.563, 0.732]
|
10 |
+
tie: [0.259, 0.255, 0.668, 0.805]
|
11 |
+
person: [0.019, 0.065, 0.962, 0.988]
|
12 |
+
person: [0.0, 0.24, 0.214, 1.0]
|
13 |
+
tie: [0.316, 0.778, 0.443, 0.867]
|
14 |
+
tie: [0.386, 0.707, 0.496, 0.801]
|
15 |
+
tie: [0.251, 0.354, 0.402, 0.747]
|
16 |
+
tie: [0.44, 0.318, 0.63, 0.397]
|
17 |
+
tie: [0.566, 0.33, 0.655, 0.543]
|
18 |
+
tie: [0.25, 0.409, 0.359, 0.556]
|
data/prompts/complex_reasoning/000_conv.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Question:
|
2 |
+
What is unusual about this photo?
|
3 |
+
===
|
4 |
+
Answer:
|
5 |
+
In the photo, the man is wearing a total of ten ties around his neck. This is considered unusual because it is not common for someone to wear multiple ties at once. In a typical setting, a person would wear only one tie. The man's goofy facial expression also adds to the unconventional and humorous nature of the image.
|
data/prompts/complex_reasoning/001_caps.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A group of people standing outside of a black vehicle with various luggage.
|
2 |
+
Luggage surrounds a vehicle in an underground parking area
|
3 |
+
People try to fit all of their luggage in an SUV.
|
4 |
+
The sport utility vehicle is parked in the public garage, being packed for a trip
|
5 |
+
Some people with luggage near a van that is transporting it.
|
6 |
+
|
7 |
+
person: [0.681, 0.242, 0.774, 0.694]
|
8 |
+
person: [0.63, 0.222, 0.686, 0.516]
|
9 |
+
person: [0.444, 0.233, 0.487, 0.34]
|
10 |
+
backpack: [0.384, 0.696, 0.485, 0.914]
|
11 |
+
backpack: [0.755, 0.413, 0.846, 0.692]
|
12 |
+
suitcase: [0.758, 0.413, 0.845, 0.69]
|
13 |
+
suitcase: [0.1, 0.497, 0.173, 0.579]
|
14 |
+
bicycle: [0.282, 0.363, 0.327, 0.442]
|
15 |
+
car: [0.786, 0.25, 0.848, 0.322]
|
16 |
+
car: [0.783, 0.27, 0.827, 0.335]
|
17 |
+
car: [0.86, 0.254, 0.891, 0.3]
|
18 |
+
car: [0.261, 0.101, 0.787, 0.626]
|
data/prompts/complex_reasoning/001_conv.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Question:
|
2 |
+
What challenges do these people face?
|
3 |
+
===
|
4 |
+
Answer:
|
5 |
+
In the image, a group of people is standing outside a black SUV in a parking area, surrounded by various pieces of luggage, including suitcases and backpacks. They are facing the challenge of fitting all their luggage into the black SUV. There are multiple suitcases and backpacks to be packed, which suggests that the group has a significant amount of belongings to accommodate. They might have to strategize and arrange the luggage efficiently to ensure that everything fits properly into the vehicle. Additionally, they need to consider the comfort of the passengers and visibility while driving, so the placement of the luggage must not obstruct the driver's view or make the passengers uncomfortable during the trip.
|
data/prompts/complex_reasoning/002_caps.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
There is a movie theater that displays the show times above the doors.
|
2 |
+
A red fire hydrant is deep in the snow.
|
3 |
+
The fire hydrant is in the snow near a recently plowed sidewalk.
|
4 |
+
This city has had a very hard winter with snow.
|
5 |
+
A hotel for dogs in the snow in winter.
|
6 |
+
|
7 |
+
fire hydrant: [0.326, 0.612, 0.426, 0.72]
|
data/prompts/complex_reasoning/002_conv.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Question:
|
2 |
+
What challenges might this city face?
|
3 |
+
===
|
4 |
+
Answer:
|
5 |
+
The city faces challenges due to the harsh winter conditions and heavy snowfall. In the image, a red fire hydrant is almost buried deep in the snow, which indicates the significant amount of snow the city has experienced. This can lead to various challenges such as difficulties in transportation, increased risk of accidents, and disruptions to daily life. For example, the recently plowed sidewalk near the fire hydrant shows that the city has to constantly clear snow from roads and sidewalks to maintain access and safety for pedestrians and vehicles. Moreover, emergency services, like firefighters, might face challenges accessing crucial equipment, such as fire hydrants, during emergencies due to the snow accumulation. This highlights the importance of effective snow management strategies and preparedness in such cities to minimize the impact of harsh winter conditions on residents and essential services.
|
data/prompts/complex_reasoning/system_message.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y.
|
2 |
+
|
3 |
+
The task is to use the provided caption and bounding box information, create a plausible question about the image, and provide the answer in detail.
|
4 |
+
|
5 |
+
Create complex questions beyond describing the scene.
|
6 |
+
To answer such questions, one should require first understanding the visual content, then based on the background knowledge or reasoning, either explain why the things are happening that way, or provide guides and help to user's request. Make the question challenging by not including the visual content details in the question so that the user needs to reason about that first.
|
7 |
+
|
8 |
+
Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects.
|
9 |
+
|
10 |
+
When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image.
|
data/prompts/conversation/000_caps.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
There is a movie theater that displays the show times above the doors.
|
2 |
+
A red fire hydrant is deep in the snow.
|
3 |
+
The fire hydrant is in the snow near a recently plowed sidewalk.
|
4 |
+
This city has had a very hard winter with snow.
|
5 |
+
A hotel for dogs in the snow in winter.
|
data/prompts/conversation/000_conv.txt
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Question:
|
2 |
+
What color is the fire hydrant in the image?
|
3 |
+
===
|
4 |
+
Answer:
|
5 |
+
The fire hydrant in the image is red.
|
6 |
+
===
|
7 |
+
Question:
|
8 |
+
Is the fire hydrant fully covered by snow or partially visible?
|
9 |
+
===
|
10 |
+
Answer:
|
11 |
+
The fire hydrant is partially visible, with a significant portion of it covered by the deep snow.
|
12 |
+
===
|
13 |
+
Question:
|
14 |
+
What is the condition of the sidewalk near the fire hydrant?
|
15 |
+
===
|
16 |
+
Answer:
|
17 |
+
The sidewalk near the fire hydrant has been recently plowed, so it is relatively clear of snow compared to the surrounding area.
|
18 |
+
===
|
19 |
+
Question:
|
20 |
+
What does the image suggest about the winter season in the city?
|
21 |
+
===
|
22 |
+
Answer:
|
23 |
+
The image suggests that the winter season in the city has been quite harsh and challenging. The significant snow accumulation seen in the image indicates that the city has experienced heavy snowfall, which can lead to various difficulties and disruptions for its residents.
|
24 |
+
|
25 |
+
For instance, the deep snow covering the fire hydrant could potentially hinder its accessibility in case of emergencies, which poses safety concerns. The recently plowed sidewalk implies that the city's maintenance crews have been actively working to keep the walkways clear and safe for pedestrians, but the sheer amount of snowfall might make it difficult to keep up with the continuous snow removal efforts.
|
26 |
+
|
27 |
+
Furthermore, such extreme winter conditions can impact transportation, leading to traffic issues, delays in public transit, and increased risks of accidents due to slippery roads. It can also cause problems for businesses and schools, as people might face challenges commuting to work or attending classes. Additionally, the heavy snow can put extra strain on infrastructure, such as roofs and power lines, increasing the likelihood of structural damage or power outages.
|
28 |
+
|
29 |
+
In conclusion, the image of the red fire hydrant deep in the snow and the recently plowed sidewalk suggest that the city has faced a particularly severe winter season, with substantial snowfall that has likely caused various challenges and disruptions for its residents and infrastructure.
|
data/prompts/conversation/001_caps.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A man is skiing in the open snow covered hills
|
2 |
+
A skier is making his way into the snow.
|
3 |
+
A skier on the foothills of a huge mountain range.
|
4 |
+
A skier looks at mountains while standing near a trail sign.
|
5 |
+
a single person skiing by an area with a lot of bushes
|
data/prompts/conversation/001_conv.txt
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Question:
|
2 |
+
What is the skier doing?
|
3 |
+
===
|
4 |
+
Answer:
|
5 |
+
The skier is skiing in the snow-covered hills, making his way through the snow and enjoying the beautiful mountain scenery. They are also standing near a trail sign, which indicates their location on the mountain.
|
6 |
+
===
|
7 |
+
Question:
|
8 |
+
Are there any other people or skiers visible in the image?
|
9 |
+
===
|
10 |
+
Answer:
|
11 |
+
No, there is only a single person skiing in the image, and they are surrounded by an area with a lot of bushes.
|
12 |
+
===
|
13 |
+
Question:
|
14 |
+
What kind of skiing is the person doing? Cross-country or downhill?
|
15 |
+
===
|
16 |
+
Answer:
|
17 |
+
Based on what I can see in the photo, it is not possible to definitively determine whether the skier is doing cross-country or downhill skiing. However, given the presence of a trail sign and the fact that they are skiing in the foothills, it is more likely that the skier is engaged in cross-country skiing. Downhill skiing typically takes place on more steep slopes and involves ski lifts, whereas cross-country skiing often occurs on relatively flatter terrain with marked trails.
|
18 |
+
===
|
19 |
+
Question:
|
20 |
+
Can you explain cross-country and downhill skiing a bit more?
|
21 |
+
===
|
22 |
+
Answer:
|
23 |
+
Cross-country skiing and downhill skiing are two distinct types of skiing, each with its own techniques, equipment, and terrain preferences.
|
24 |
+
|
25 |
+
1. Cross-Country Skiing:
|
26 |
+
Also known as Nordic skiing, cross-country skiing involves traversing relatively flat terrain or gentle slopes using skis and poles. It is a popular recreational and competitive sport that focuses on endurance, balance, and aerobic fitness. Cross-country skiers use their own locomotion to move across snow-covered terrain, rather than relying on ski lifts or other forms of assistance.
|
27 |
+
There are two main techniques in cross-country skiing:
|
28 |
+
- Classic: This technique involves skiing in parallel tracks, using a forward-and-backward gliding motion while keeping the skis parallel to each other. The skier uses their poles to propel themselves forward.
|
29 |
+
- Skate skiing: This technique is similar to ice skating, where the skier pushes off one ski at an angle and glides on the other. It requires a smooth, groomed surface and is typically faster than the classic technique.
|
30 |
+
Cross-country ski equipment consists of lightweight skis, boots, bindings, and poles. The boots are more flexible than those used in downhill skiing, allowing for better ankle movement and control.
|
31 |
+
|
32 |
+
2. Downhill Skiing:
|
33 |
+
Also known as alpine skiing, downhill skiing involves descending slopes at high speeds using skis and poles for balance and control. This sport is more focused on speed, technique, and navigating challenging terrain, including steep slopes, moguls, and even jumps.
|
34 |
+
Downhill skiing can be further categorized into several disciplines, such as slalom, giant slalom, super-G, and downhill racing. Each discipline has its own set of rules, courses, and ski equipment.
|
35 |
+
Downhill ski equipment includes heavier and stiffer skis, boots, bindings, and poles than those used in cross-country skiing. The boots are more rigid to provide better support and control during high-speed descents and sharp turns.
|
36 |
+
|
37 |
+
In summary, cross-country skiing is an endurance-based sport that involves traveling across flat or gently sloping terrain, while downhill skiing is focused on speed and technique as skiers navigate steeper slopes and challenging terrain. Both sports require specialized equipment and techniques, but they offer different experiences and challenges to participants.
|
data/prompts/conversation/system_message.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are an AI visual assistant, and you are seeing a single image. What you see are provided with five sentences, describing the same image you are looking at. Answer all questions as you are seeing the image.
|
2 |
+
|
3 |
+
Design a conversation between you and a person asking about this photo. The answers should be in a tone that a visual AI assistant is seeing the image and answering the question.
|
4 |
+
Ask diverse questions and give corresponding answers.
|
5 |
+
|
6 |
+
Include questions asking about the visual content of the image, including the object types, counting the objects, object actions, object locations, relative positions between objects, etc. Only include questions that have definite answers:
|
7 |
+
(1) one can see the content in the image that the question asks about and can answer confidently;
|
8 |
+
(2) one can determine confidently from the image that it is not in the image.
|
9 |
+
Do not ask any question that cannot be answered confidently.
|
10 |
+
|
11 |
+
Also include complex questions that are relevant to the content in the image, for example, asking about background knowledge of the objects in the image, asking to discuss about events happening in the image, etc. Again, do not ask about uncertain details.
|
12 |
+
Provide detailed answers when answering complex questions. For example, give detailed examples or reasoning steps to make the content more convincing and well-organized. You can include multiple paragraphs if necessary.
|
data/prompts/detail_description/000_caps.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A harbor filled with lots of boats next to a building.
|
2 |
+
A bicycle parked in front of several boats at a dock.
|
3 |
+
A red bicycle in front of a line of docked white yachts
|
4 |
+
A bike sits before boats which sit before a long building.
|
5 |
+
A bicycle is a convenient means of land transportation when you live on a boat.
|
6 |
+
|
7 |
+
bicycle: [0.287, 0.641, 0.507, 0.874]
|
8 |
+
bicycle: [0.566, 0.667, 0.63, 0.731]
|
9 |
+
boat: [0.318, 0.579, 0.575, 0.724]
|
10 |
+
boat: [0.704, 0.607, 0.818, 0.727]
|
11 |
+
boat: [0.818, 0.601, 0.942, 0.744]
|
12 |
+
boat: [0.002, 0.53, 0.243, 0.71]
|
13 |
+
boat: [0.541, 0.611, 0.668, 0.731]
|
14 |
+
person: [0.778, 0.527, 0.797, 0.57]
|
15 |
+
cup: [0.708, 0.733, 0.724, 0.758]
|
16 |
+
boat: [0.236, 0.532, 0.404, 0.64]
|
17 |
+
boat: [0.81, 0.632, 0.836, 0.676]
|
18 |
+
boat: [0.957, 0.526, 1.0, 0.752]
|
data/prompts/detail_description/000_conv.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
It is a harbor filled with numerous boats of various sizes docked next to a long building. Among the boats, there are a few white yachts lined up, standing out from the rest. There is a red bicycle prominently parked in front of the line of docked boats, serving as a convenient means of land transportation for those living on the boats. Another bicycle can be seen further back in the scene, near the middle of the harbor.
|
2 |
+
|
3 |
+
A person is visible near the right side of the harbor, possibly enjoying the view or attending to their boat. Additionally, there is a cup placed on a surface near the middle of the scene.
|
data/prompts/detail_description/001_caps.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A group of people standing outside of a black vehicle with various luggage.
|
2 |
+
Luggage surrounds a vehicle in an underground parking area
|
3 |
+
People try to fit all of their luggage in an SUV.
|
4 |
+
The sport utility vehicle is parked in the public garage, being packed for a trip
|
5 |
+
Some people with luggage near a van that is transporting it.
|
6 |
+
|
7 |
+
person: [0.681, 0.242, 0.774, 0.694]
|
8 |
+
person: [0.63, 0.222, 0.686, 0.516]
|
9 |
+
person: [0.444, 0.233, 0.487, 0.34]
|
10 |
+
backpack: [0.384, 0.696, 0.485, 0.914]
|
11 |
+
backpack: [0.755, 0.413, 0.846, 0.692]
|
12 |
+
suitcase: [0.758, 0.413, 0.845, 0.69]
|
13 |
+
suitcase: [0.1, 0.497, 0.173, 0.579]
|
14 |
+
bicycle: [0.282, 0.363, 0.327, 0.442]
|
15 |
+
car: [0.786, 0.25, 0.848, 0.322]
|
16 |
+
car: [0.783, 0.27, 0.827, 0.335]
|
17 |
+
car: [0.86, 0.254, 0.891, 0.3]
|
18 |
+
car: [0.261, 0.101, 0.787, 0.626]
|
data/prompts/detail_description/001_conv.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The image is an underground parking area with a black sport utility vehicle (SUV) parked. There are three people in the scene, with one person standing closer to the left side of the vehicle, another person in the middle, and the third person on the right side. They are all working together to pack their luggage into the SUV for a trip.
|
2 |
+
|
3 |
+
In the parking area, various luggage items are scattered around the vehicle. There are two backpacks, one located near the left rear wheel and the other closer to the right side of the vehicle. Additionally, there are two suitcases, one on the right side of the car and another further away near the center of the parking area. A bicycle can also be seen on the left side of the vehicle.
|
4 |
+
|
5 |
+
Other cars are parked around the main SUV, with one car positioned behind it and slightly to the left, another behind and slightly to the right, and the third car further behind on the right side.
|
data/prompts/detail_description/002_caps.txt
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
A man holds a Wii-mote above his head while another looks on.
|
2 |
+
A guy and his friend are playing Nintendo Wii.
|
3 |
+
A young man is holding a video game remote over his head.
|
4 |
+
two men standing in a room while one plays with a wii mote
|
5 |
+
Some guys standing and playing a video game.
|
6 |
+
|
7 |
+
couch: [0.697, 0.759, 0.995, 1.0]
|
8 |
+
dining table: [0.426, 0.755, 1.0, 0.987]
|
9 |
+
person: [0.082, 0.252, 0.342, 1.0]
|
10 |
+
person: [0.399, 0.085, 0.742, 0.982]
|
11 |
+
remote: [0.477, 0.135, 0.516, 0.187]
|
12 |
+
sink: [0.016, 0.501, 0.063, 0.52]
|
13 |
+
potted plant: [0.798, 0.384, 0.888, 0.645]
|
14 |
+
refrigerator: [0.305, 0.389, 0.414, 0.547]
|
15 |
+
chair: [0.72, 0.509, 0.858, 0.725]
|
data/prompts/detail_description/002_conv.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
The image shows two men standing in a room, engaged in playing a video game on a Nintendo Wii console. One of the men is holding a Wii remote above his head with enthusiasm, while the other man looks on, likely enjoying the friendly competition.
|
2 |
+
|
3 |
+
The room appears to be a living space with a couch located in the background and a dining table nearby. A potted plant can be seen placed close to the couch, and a chair is situated in the middle of the room. The room also features a kitchen area with a sink and a refrigerator visible in the background.
|
data/prompts/detail_description/system_message.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are an AI visual assistant that can analyze a single image. You receive five sentences, each describing the same image you are observing. In addition, specific object locations within the image are given, along with detailed coordinates. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y.
|
2 |
+
|
3 |
+
Using the provided caption and bounding box information, describe the scene in a detailed manner.
|
4 |
+
|
5 |
+
Instead of directly mentioning the bounding box coordinates, utilize this data to explain the scene using natural language. Include details like object counts, position of the objects, relative position between the objects.
|
6 |
+
|
7 |
+
When using the information from the caption and coordinates, directly explain the scene, and do not mention that the information source is the caption or the bounding box. Always answer as if you are directly looking at the image.
|
llava/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .model import LlavaLlamaForCausalLM
|
llava/constants.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
5 |
+
|
6 |
+
# Model Constants
|
7 |
+
IGNORE_INDEX = -100
|
8 |
+
IMAGE_TOKEN_INDEX = -200
|
9 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
10 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
11 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
12 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
llava/conversation.py
ADDED
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import auto, Enum
|
3 |
+
from typing import List, Tuple
|
4 |
+
|
5 |
+
|
6 |
+
class SeparatorStyle(Enum):
|
7 |
+
"""Different separator style."""
|
8 |
+
SINGLE = auto()
|
9 |
+
TWO = auto()
|
10 |
+
MPT = auto()
|
11 |
+
PLAIN = auto()
|
12 |
+
LLAMA_2 = auto()
|
13 |
+
|
14 |
+
|
15 |
+
@dataclasses.dataclass
|
16 |
+
class Conversation:
|
17 |
+
"""A class that keeps all conversation history."""
|
18 |
+
system: str
|
19 |
+
roles: List[str]
|
20 |
+
messages: List[List[str]]
|
21 |
+
offset: int
|
22 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
23 |
+
sep: str = "###"
|
24 |
+
sep2: str = None
|
25 |
+
version: str = "Unknown"
|
26 |
+
|
27 |
+
skip_next: bool = False
|
28 |
+
|
29 |
+
def get_prompt(self):
|
30 |
+
messages = self.messages
|
31 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
32 |
+
messages = self.messages.copy()
|
33 |
+
init_role, init_msg = messages[0].copy()
|
34 |
+
init_msg = init_msg[0].replace("<image>", "").strip()
|
35 |
+
if 'mmtag' in self.version:
|
36 |
+
messages[0] = (init_role, init_msg)
|
37 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
38 |
+
messages.insert(1, (self.roles[1], "Received."))
|
39 |
+
else:
|
40 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
41 |
+
|
42 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
43 |
+
ret = self.system + self.sep
|
44 |
+
for role, message in messages:
|
45 |
+
if message:
|
46 |
+
if type(message) is tuple:
|
47 |
+
message, _, _ = message
|
48 |
+
ret += role + ": " + message + self.sep
|
49 |
+
else:
|
50 |
+
ret += role + ":"
|
51 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
52 |
+
seps = [self.sep, self.sep2]
|
53 |
+
ret = self.system + seps[0]
|
54 |
+
for i, (role, message) in enumerate(messages):
|
55 |
+
if message:
|
56 |
+
if type(message) is tuple:
|
57 |
+
message, _, _ = message
|
58 |
+
ret += role + ": " + message + seps[i % 2]
|
59 |
+
else:
|
60 |
+
ret += role + ":"
|
61 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
62 |
+
ret = self.system + self.sep
|
63 |
+
for role, message in messages:
|
64 |
+
if message:
|
65 |
+
if type(message) is tuple:
|
66 |
+
message, _, _ = message
|
67 |
+
ret += role + message + self.sep
|
68 |
+
else:
|
69 |
+
ret += role
|
70 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
71 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
72 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
73 |
+
ret = ""
|
74 |
+
|
75 |
+
for i, (role, message) in enumerate(messages):
|
76 |
+
if i == 0:
|
77 |
+
assert message, "first message should not be none"
|
78 |
+
assert role == self.roles[0], "first message should come from user"
|
79 |
+
if message:
|
80 |
+
if type(message) is tuple:
|
81 |
+
message, _, _ = message
|
82 |
+
if i == 0: message = wrap_sys(self.system) + message
|
83 |
+
if i % 2 == 0:
|
84 |
+
message = wrap_inst(message)
|
85 |
+
ret += self.sep + message
|
86 |
+
else:
|
87 |
+
ret += " " + message + " " + self.sep2
|
88 |
+
else:
|
89 |
+
ret += ""
|
90 |
+
ret = ret.lstrip(self.sep)
|
91 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
92 |
+
seps = [self.sep, self.sep2]
|
93 |
+
ret = self.system
|
94 |
+
for i, (role, message) in enumerate(messages):
|
95 |
+
if message:
|
96 |
+
if type(message) is tuple:
|
97 |
+
message, _, _ = message
|
98 |
+
ret += message + seps[i % 2]
|
99 |
+
else:
|
100 |
+
ret += ""
|
101 |
+
else:
|
102 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
103 |
+
|
104 |
+
return ret
|
105 |
+
|
106 |
+
def append_message(self, role, message):
|
107 |
+
self.messages.append([role, message])
|
108 |
+
|
109 |
+
def get_images(self, return_pil=False):
|
110 |
+
images = []
|
111 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
112 |
+
if i % 2 == 0:
|
113 |
+
if type(msg) is tuple:
|
114 |
+
import base64
|
115 |
+
from io import BytesIO
|
116 |
+
from PIL import Image
|
117 |
+
msg, image, image_process_mode = msg
|
118 |
+
if image_process_mode == "Pad":
|
119 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
120 |
+
width, height = pil_img.size
|
121 |
+
if width == height:
|
122 |
+
return pil_img
|
123 |
+
elif width > height:
|
124 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
125 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
126 |
+
return result
|
127 |
+
else:
|
128 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
129 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
130 |
+
return result
|
131 |
+
image = expand2square(image)
|
132 |
+
elif image_process_mode in ["Default", "Crop"]:
|
133 |
+
pass
|
134 |
+
elif image_process_mode == "Resize":
|
135 |
+
image = image.resize((336, 336))
|
136 |
+
else:
|
137 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
138 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
139 |
+
aspect_ratio = max_hw / min_hw
|
140 |
+
max_len, min_len = 800, 400
|
141 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
142 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
143 |
+
W, H = image.size
|
144 |
+
if longest_edge != max(image.size):
|
145 |
+
if H > W:
|
146 |
+
H, W = longest_edge, shortest_edge
|
147 |
+
else:
|
148 |
+
H, W = shortest_edge, longest_edge
|
149 |
+
image = image.resize((W, H))
|
150 |
+
if return_pil:
|
151 |
+
images.append(image)
|
152 |
+
else:
|
153 |
+
buffered = BytesIO()
|
154 |
+
image.save(buffered, format="PNG")
|
155 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
156 |
+
images.append(img_b64_str)
|
157 |
+
return images
|
158 |
+
|
159 |
+
def to_gradio_chatbot(self):
|
160 |
+
ret = []
|
161 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
162 |
+
if i % 2 == 0:
|
163 |
+
if type(msg) is tuple:
|
164 |
+
import base64
|
165 |
+
from io import BytesIO
|
166 |
+
msg, image, image_process_mode = msg
|
167 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
168 |
+
aspect_ratio = max_hw / min_hw
|
169 |
+
max_len, min_len = 800, 400
|
170 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
171 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
172 |
+
W, H = image.size
|
173 |
+
if H > W:
|
174 |
+
H, W = longest_edge, shortest_edge
|
175 |
+
else:
|
176 |
+
H, W = shortest_edge, longest_edge
|
177 |
+
image = image.resize((W, H))
|
178 |
+
buffered = BytesIO()
|
179 |
+
image.save(buffered, format="JPEG")
|
180 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
181 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
182 |
+
msg = img_str + msg.replace('<image>', '').strip()
|
183 |
+
ret.append([msg, None])
|
184 |
+
else:
|
185 |
+
ret.append([msg, None])
|
186 |
+
else:
|
187 |
+
ret[-1][-1] = msg
|
188 |
+
return ret
|
189 |
+
|
190 |
+
def copy(self):
|
191 |
+
return Conversation(
|
192 |
+
system=self.system,
|
193 |
+
roles=self.roles,
|
194 |
+
messages=[[x, y] for x, y in self.messages],
|
195 |
+
offset=self.offset,
|
196 |
+
sep_style=self.sep_style,
|
197 |
+
sep=self.sep,
|
198 |
+
sep2=self.sep2,
|
199 |
+
version=self.version)
|
200 |
+
|
201 |
+
def dict(self):
|
202 |
+
if len(self.get_images()) > 0:
|
203 |
+
return {
|
204 |
+
"system": self.system,
|
205 |
+
"roles": self.roles,
|
206 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
207 |
+
"offset": self.offset,
|
208 |
+
"sep": self.sep,
|
209 |
+
"sep2": self.sep2,
|
210 |
+
}
|
211 |
+
return {
|
212 |
+
"system": self.system,
|
213 |
+
"roles": self.roles,
|
214 |
+
"messages": self.messages,
|
215 |
+
"offset": self.offset,
|
216 |
+
"sep": self.sep,
|
217 |
+
"sep2": self.sep2,
|
218 |
+
}
|
219 |
+
|
220 |
+
|
221 |
+
conv_vicuna_v0 = Conversation(
|
222 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
223 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
224 |
+
roles=("Human", "Assistant"),
|
225 |
+
messages=(
|
226 |
+
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
227 |
+
("Assistant",
|
228 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
229 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
230 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
231 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
232 |
+
"renewable and non-renewable energy sources:\n"
|
233 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
234 |
+
"energy sources are finite and will eventually run out.\n"
|
235 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
236 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
237 |
+
"and other negative effects.\n"
|
238 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
239 |
+
"have lower operational costs than non-renewable sources.\n"
|
240 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
241 |
+
"locations than non-renewable sources.\n"
|
242 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
243 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
244 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
245 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
246 |
+
),
|
247 |
+
offset=2,
|
248 |
+
sep_style=SeparatorStyle.SINGLE,
|
249 |
+
sep="###",
|
250 |
+
)
|
251 |
+
|
252 |
+
conv_vicuna_v1 = Conversation(
|
253 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
254 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
255 |
+
roles=("USER", "ASSISTANT"),
|
256 |
+
version="v1",
|
257 |
+
messages=(),
|
258 |
+
offset=0,
|
259 |
+
sep_style=SeparatorStyle.TWO,
|
260 |
+
sep=" ",
|
261 |
+
sep2="</s>",
|
262 |
+
)
|
263 |
+
|
264 |
+
conv_llama_2 = Conversation(
|
265 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
266 |
+
|
267 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
268 |
+
roles=("USER", "ASSISTANT"),
|
269 |
+
version="llama_v2",
|
270 |
+
messages=(),
|
271 |
+
offset=0,
|
272 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
273 |
+
sep="<s>",
|
274 |
+
sep2="</s>",
|
275 |
+
)
|
276 |
+
|
277 |
+
conv_llava_llama_2 = Conversation(
|
278 |
+
system="You are a helpful language and vision assistant. "
|
279 |
+
"You are able to understand the visual content that the user provides, "
|
280 |
+
"and assist the user with a variety of tasks using natural language.",
|
281 |
+
roles=("USER", "ASSISTANT"),
|
282 |
+
version="llama_v2",
|
283 |
+
messages=(),
|
284 |
+
offset=0,
|
285 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
286 |
+
sep="<s>",
|
287 |
+
sep2="</s>",
|
288 |
+
)
|
289 |
+
|
290 |
+
conv_mpt = Conversation(
|
291 |
+
system="""<|im_start|>system
|
292 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
293 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
294 |
+
version="mpt",
|
295 |
+
messages=(),
|
296 |
+
offset=0,
|
297 |
+
sep_style=SeparatorStyle.MPT,
|
298 |
+
sep="<|im_end|>",
|
299 |
+
)
|
300 |
+
|
301 |
+
conv_llava_plain = Conversation(
|
302 |
+
system="",
|
303 |
+
roles=("", ""),
|
304 |
+
messages=(
|
305 |
+
),
|
306 |
+
offset=0,
|
307 |
+
sep_style=SeparatorStyle.PLAIN,
|
308 |
+
sep="\n",
|
309 |
+
)
|
310 |
+
|
311 |
+
conv_llava_v0 = Conversation(
|
312 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
313 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
314 |
+
roles=("Human", "Assistant"),
|
315 |
+
messages=(
|
316 |
+
),
|
317 |
+
offset=0,
|
318 |
+
sep_style=SeparatorStyle.SINGLE,
|
319 |
+
sep="###",
|
320 |
+
)
|
321 |
+
|
322 |
+
conv_llava_v0_mmtag = Conversation(
|
323 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
324 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
325 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
326 |
+
roles=("Human", "Assistant"),
|
327 |
+
messages=(
|
328 |
+
),
|
329 |
+
offset=0,
|
330 |
+
sep_style=SeparatorStyle.SINGLE,
|
331 |
+
sep="###",
|
332 |
+
version="v0_mmtag",
|
333 |
+
)
|
334 |
+
|
335 |
+
conv_llava_v1 = Conversation(
|
336 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
337 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
338 |
+
roles=("USER", "ASSISTANT"),
|
339 |
+
version="v1",
|
340 |
+
messages=(),
|
341 |
+
offset=0,
|
342 |
+
sep_style=SeparatorStyle.TWO,
|
343 |
+
sep=" ",
|
344 |
+
sep2="</s>",
|
345 |
+
)
|
346 |
+
|
347 |
+
conv_llava_v1_mmtag = Conversation(
|
348 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
349 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
350 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
351 |
+
roles=("USER", "ASSISTANT"),
|
352 |
+
messages=(),
|
353 |
+
offset=0,
|
354 |
+
sep_style=SeparatorStyle.TWO,
|
355 |
+
sep=" ",
|
356 |
+
sep2="</s>",
|
357 |
+
version="v1_mmtag",
|
358 |
+
)
|
359 |
+
|
360 |
+
default_conversation = conv_vicuna_v0
|
361 |
+
conv_templates = {
|
362 |
+
"default": conv_vicuna_v0,
|
363 |
+
"v0": conv_vicuna_v0,
|
364 |
+
"v1": conv_vicuna_v1,
|
365 |
+
"vicuna_v1": conv_vicuna_v1,
|
366 |
+
"llama_2": conv_llama_2,
|
367 |
+
|
368 |
+
"plain": conv_llava_plain,
|
369 |
+
"v0_plain": conv_llava_plain,
|
370 |
+
"llava_v0": conv_llava_v0,
|
371 |
+
"v0_mmtag": conv_llava_v0_mmtag,
|
372 |
+
"llava_v1": conv_llava_v1,
|
373 |
+
"v1_mmtag": conv_llava_v1_mmtag,
|
374 |
+
"llava_llama_2": conv_llava_llama_2,
|
375 |
+
|
376 |
+
"mpt": conv_mpt,
|
377 |
+
}
|
378 |
+
|
379 |
+
|
380 |
+
if __name__ == "__main__":
|
381 |
+
print(default_conversation.get_prompt())
|
llava/eval/eval_gpt_review.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
|
5 |
+
import openai
|
6 |
+
import tqdm
|
7 |
+
import ray
|
8 |
+
import time
|
9 |
+
|
10 |
+
NUM_SECONDS_TO_SLEEP = 3
|
11 |
+
|
12 |
+
@ray.remote(num_cpus=4)
|
13 |
+
def get_eval(content: str, max_tokens: int):
|
14 |
+
while True:
|
15 |
+
try:
|
16 |
+
response = openai.ChatCompletion.create(
|
17 |
+
model='gpt-4',
|
18 |
+
messages=[{
|
19 |
+
'role': 'system',
|
20 |
+
'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
|
21 |
+
}, {
|
22 |
+
'role': 'user',
|
23 |
+
'content': content,
|
24 |
+
}],
|
25 |
+
temperature=0.2, # TODO: figure out which temperature is best for evaluation
|
26 |
+
max_tokens=max_tokens,
|
27 |
+
)
|
28 |
+
break
|
29 |
+
except openai.error.RateLimitError:
|
30 |
+
pass
|
31 |
+
except Exception as e:
|
32 |
+
print(e)
|
33 |
+
time.sleep(NUM_SECONDS_TO_SLEEP)
|
34 |
+
|
35 |
+
print('success!')
|
36 |
+
return response['choices'][0]['message']['content']
|
37 |
+
|
38 |
+
|
39 |
+
def parse_score(review):
|
40 |
+
try:
|
41 |
+
score_pair = review.split('\n')[0]
|
42 |
+
score_pair = score_pair.replace(',', ' ')
|
43 |
+
sp = score_pair.split(' ')
|
44 |
+
if len(sp) == 2:
|
45 |
+
return [float(sp[0]), float(sp[1])]
|
46 |
+
else:
|
47 |
+
print('error', review)
|
48 |
+
return [-1, -1]
|
49 |
+
except Exception as e:
|
50 |
+
print(e)
|
51 |
+
print('error', review)
|
52 |
+
return [-1, -1]
|
53 |
+
|
54 |
+
|
55 |
+
if __name__ == '__main__':
|
56 |
+
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
57 |
+
parser.add_argument('-q', '--question')
|
58 |
+
# parser.add_argument('-a', '--answer')
|
59 |
+
parser.add_argument('-a', '--answer-list', nargs='+', default=[])
|
60 |
+
parser.add_argument('-r', '--rule')
|
61 |
+
parser.add_argument('-o', '--output')
|
62 |
+
parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
|
63 |
+
args = parser.parse_args()
|
64 |
+
|
65 |
+
ray.init()
|
66 |
+
|
67 |
+
f_q = open(os.path.expanduser(args.question))
|
68 |
+
f_ans1 = open(os.path.expanduser(args.answer_list[0]))
|
69 |
+
f_ans2 = open(os.path.expanduser(args.answer_list[1]))
|
70 |
+
rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
|
71 |
+
|
72 |
+
review_file = open(f'{args.output}', 'w')
|
73 |
+
|
74 |
+
js_list = []
|
75 |
+
handles = []
|
76 |
+
idx = 0
|
77 |
+
for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
|
78 |
+
# if idx == 1:
|
79 |
+
# break
|
80 |
+
|
81 |
+
ques = json.loads(ques_js)
|
82 |
+
ans1 = json.loads(ans1_js)
|
83 |
+
ans2 = json.loads(ans2_js)
|
84 |
+
|
85 |
+
category = json.loads(ques_js)['category']
|
86 |
+
if category in rule_dict:
|
87 |
+
rule = rule_dict[category]
|
88 |
+
else:
|
89 |
+
rule = rule_dict['default']
|
90 |
+
prompt = rule['prompt']
|
91 |
+
role = rule['role']
|
92 |
+
content = (f'[Question]\n{ques["text"]}\n\n'
|
93 |
+
f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
|
94 |
+
f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
|
95 |
+
f'[System]\n{prompt}\n\n')
|
96 |
+
js_list.append({
|
97 |
+
'id': idx+1,
|
98 |
+
'question_id': ques['question_id'],
|
99 |
+
'answer1_id': ans1['answer_id'],
|
100 |
+
'answer2_id': ans2['answer_id'],
|
101 |
+
'category': category})
|
102 |
+
idx += 1
|
103 |
+
handles.append(get_eval.remote(content, args.max_tokens))
|
104 |
+
# To avoid the rate limit set by OpenAI
|
105 |
+
time.sleep(NUM_SECONDS_TO_SLEEP)
|
106 |
+
|
107 |
+
reviews = ray.get(handles)
|
108 |
+
for idx, review in enumerate(reviews):
|
109 |
+
scores = parse_score(review)
|
110 |
+
js_list[idx]['content'] = review
|
111 |
+
js_list[idx]['tuple'] = scores
|
112 |
+
review_file.write(json.dumps(js_list[idx]) + '\n')
|
113 |
+
review_file.close()
|
llava/eval/eval_gpt_review_bench.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
|
5 |
+
import openai
|
6 |
+
import time
|
7 |
+
|
8 |
+
NUM_SECONDS_TO_SLEEP = 0.5
|
9 |
+
|
10 |
+
|
11 |
+
def get_eval(content: str, max_tokens: int):
|
12 |
+
while True:
|
13 |
+
try:
|
14 |
+
response = openai.ChatCompletion.create(
|
15 |
+
model='gpt-4-0314',
|
16 |
+
messages=[{
|
17 |
+
'role': 'system',
|
18 |
+
'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
|
19 |
+
}, {
|
20 |
+
'role': 'user',
|
21 |
+
'content': content,
|
22 |
+
}],
|
23 |
+
temperature=0.2, # TODO: figure out which temperature is best for evaluation
|
24 |
+
max_tokens=max_tokens,
|
25 |
+
)
|
26 |
+
break
|
27 |
+
except openai.error.RateLimitError:
|
28 |
+
pass
|
29 |
+
except Exception as e:
|
30 |
+
print(e)
|
31 |
+
time.sleep(NUM_SECONDS_TO_SLEEP)
|
32 |
+
|
33 |
+
return response['choices'][0]['message']['content']
|
34 |
+
|
35 |
+
|
36 |
+
def parse_score(review):
|
37 |
+
try:
|
38 |
+
score_pair = review.split('\n')[0]
|
39 |
+
score_pair = score_pair.replace(',', ' ')
|
40 |
+
sp = score_pair.split(' ')
|
41 |
+
if len(sp) == 2:
|
42 |
+
return [float(sp[0]), float(sp[1])]
|
43 |
+
else:
|
44 |
+
print('error', review)
|
45 |
+
return [-1, -1]
|
46 |
+
except Exception as e:
|
47 |
+
print(e)
|
48 |
+
print('error', review)
|
49 |
+
return [-1, -1]
|
50 |
+
|
51 |
+
|
52 |
+
if __name__ == '__main__':
|
53 |
+
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
54 |
+
parser.add_argument('-q', '--question')
|
55 |
+
parser.add_argument('-c', '--context')
|
56 |
+
parser.add_argument('-a', '--answer-list', nargs='+', default=[])
|
57 |
+
parser.add_argument('-r', '--rule')
|
58 |
+
parser.add_argument('-o', '--output')
|
59 |
+
parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
|
60 |
+
args = parser.parse_args()
|
61 |
+
|
62 |
+
f_q = open(os.path.expanduser(args.question))
|
63 |
+
f_ans1 = open(os.path.expanduser(args.answer_list[0]))
|
64 |
+
f_ans2 = open(os.path.expanduser(args.answer_list[1]))
|
65 |
+
rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
|
66 |
+
|
67 |
+
if os.path.isfile(os.path.expanduser(args.output)):
|
68 |
+
cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))]
|
69 |
+
else:
|
70 |
+
cur_reviews = []
|
71 |
+
|
72 |
+
review_file = open(f'{args.output}', 'a')
|
73 |
+
|
74 |
+
context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))]
|
75 |
+
image_to_context = {context['image']: context for context in context_list}
|
76 |
+
|
77 |
+
handles = []
|
78 |
+
idx = 0
|
79 |
+
for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
|
80 |
+
ques = json.loads(ques_js)
|
81 |
+
ans1 = json.loads(ans1_js)
|
82 |
+
ans2 = json.loads(ans2_js)
|
83 |
+
|
84 |
+
inst = image_to_context[ques['image']]
|
85 |
+
|
86 |
+
if isinstance(inst['caption'], list):
|
87 |
+
cap_str = '\n'.join(inst['caption'])
|
88 |
+
else:
|
89 |
+
cap_str = inst['caption']
|
90 |
+
|
91 |
+
category = 'llava_bench_' + json.loads(ques_js)['category']
|
92 |
+
if category in rule_dict:
|
93 |
+
rule = rule_dict[category]
|
94 |
+
else:
|
95 |
+
assert False, f"Visual QA category not found in rule file: {category}."
|
96 |
+
prompt = rule['prompt']
|
97 |
+
role = rule['role']
|
98 |
+
content = (f'[Context]\n{cap_str}\n\n'
|
99 |
+
f'[Question]\n{ques["text"]}\n\n'
|
100 |
+
f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
|
101 |
+
f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
|
102 |
+
f'[System]\n{prompt}\n\n')
|
103 |
+
cur_js = {
|
104 |
+
'id': idx+1,
|
105 |
+
'question_id': ques['question_id'],
|
106 |
+
'answer1_id': ans1.get('answer_id', ans1['question_id']),
|
107 |
+
'answer2_id': ans2.get('answer_id', ans2['answer_id']),
|
108 |
+
'category': category
|
109 |
+
}
|
110 |
+
if idx >= len(cur_reviews):
|
111 |
+
review = get_eval(content, args.max_tokens)
|
112 |
+
scores = parse_score(review)
|
113 |
+
cur_js['content'] = review
|
114 |
+
cur_js['tuple'] = scores
|
115 |
+
review_file.write(json.dumps(cur_js) + '\n')
|
116 |
+
review_file.flush()
|
117 |
+
else:
|
118 |
+
print(f'Skipping {idx} as we already have it.')
|
119 |
+
idx += 1
|
120 |
+
print(idx)
|
121 |
+
review_file.close()
|
llava/eval/eval_gpt_review_visual.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
|
5 |
+
import openai
|
6 |
+
import time
|
7 |
+
|
8 |
+
NUM_SECONDS_TO_SLEEP = 0.5
|
9 |
+
|
10 |
+
|
11 |
+
def get_eval(content: str, max_tokens: int):
|
12 |
+
while True:
|
13 |
+
try:
|
14 |
+
response = openai.ChatCompletion.create(
|
15 |
+
model='gpt-4-0314',
|
16 |
+
messages=[{
|
17 |
+
'role': 'system',
|
18 |
+
'content': 'You are a helpful and precise assistant for checking the quality of the answer.'
|
19 |
+
}, {
|
20 |
+
'role': 'user',
|
21 |
+
'content': content,
|
22 |
+
}],
|
23 |
+
temperature=0.2, # TODO: figure out which temperature is best for evaluation
|
24 |
+
max_tokens=max_tokens,
|
25 |
+
)
|
26 |
+
break
|
27 |
+
except openai.error.RateLimitError:
|
28 |
+
pass
|
29 |
+
except Exception as e:
|
30 |
+
print(e)
|
31 |
+
time.sleep(NUM_SECONDS_TO_SLEEP)
|
32 |
+
|
33 |
+
return response['choices'][0]['message']['content']
|
34 |
+
|
35 |
+
|
36 |
+
def parse_score(review):
|
37 |
+
try:
|
38 |
+
score_pair = review.split('\n')[0]
|
39 |
+
score_pair = score_pair.replace(',', ' ')
|
40 |
+
sp = score_pair.split(' ')
|
41 |
+
if len(sp) == 2:
|
42 |
+
return [float(sp[0]), float(sp[1])]
|
43 |
+
else:
|
44 |
+
print('error', review)
|
45 |
+
return [-1, -1]
|
46 |
+
except Exception as e:
|
47 |
+
print(e)
|
48 |
+
print('error', review)
|
49 |
+
return [-1, -1]
|
50 |
+
|
51 |
+
|
52 |
+
if __name__ == '__main__':
|
53 |
+
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
54 |
+
parser.add_argument('-q', '--question')
|
55 |
+
parser.add_argument('-c', '--context')
|
56 |
+
parser.add_argument('-a', '--answer-list', nargs='+', default=[])
|
57 |
+
parser.add_argument('-r', '--rule')
|
58 |
+
parser.add_argument('-o', '--output')
|
59 |
+
parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
|
60 |
+
args = parser.parse_args()
|
61 |
+
|
62 |
+
f_q = open(os.path.expanduser(args.question))
|
63 |
+
f_ans1 = open(os.path.expanduser(args.answer_list[0]))
|
64 |
+
f_ans2 = open(os.path.expanduser(args.answer_list[1]))
|
65 |
+
rule_dict = json.load(open(os.path.expanduser(args.rule), 'r'))
|
66 |
+
|
67 |
+
if os.path.isfile(os.path.expanduser(args.output)):
|
68 |
+
cur_reviews = [json.loads(line) for line in open(os.path.expanduser(args.output))]
|
69 |
+
else:
|
70 |
+
cur_reviews = []
|
71 |
+
|
72 |
+
review_file = open(f'{args.output}', 'a')
|
73 |
+
|
74 |
+
context_list = [json.loads(line) for line in open(os.path.expanduser(args.context))]
|
75 |
+
image_to_context = {context['image']: context for context in context_list}
|
76 |
+
|
77 |
+
handles = []
|
78 |
+
idx = 0
|
79 |
+
for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):
|
80 |
+
ques = json.loads(ques_js)
|
81 |
+
ans1 = json.loads(ans1_js)
|
82 |
+
ans2 = json.loads(ans2_js)
|
83 |
+
|
84 |
+
inst = image_to_context[ques['image']]
|
85 |
+
cap_str = '\n'.join(inst['captions'])
|
86 |
+
box_str = '\n'.join([f'{instance["category"]}: {instance["bbox"]}' for instance in inst['instances']])
|
87 |
+
|
88 |
+
category = json.loads(ques_js)['category']
|
89 |
+
if category in rule_dict:
|
90 |
+
rule = rule_dict[category]
|
91 |
+
else:
|
92 |
+
assert False, f"Visual QA category not found in rule file: {category}."
|
93 |
+
prompt = rule['prompt']
|
94 |
+
role = rule['role']
|
95 |
+
content = (f'[Context]\n{cap_str}\n\n{box_str}\n\n'
|
96 |
+
f'[Question]\n{ques["text"]}\n\n'
|
97 |
+
f'[{role} 1]\n{ans1["text"]}\n\n[End of {role} 1]\n\n'
|
98 |
+
f'[{role} 2]\n{ans2["text"]}\n\n[End of {role} 2]\n\n'
|
99 |
+
f'[System]\n{prompt}\n\n')
|
100 |
+
cur_js = {
|
101 |
+
'id': idx+1,
|
102 |
+
'question_id': ques['question_id'],
|
103 |
+
'answer1_id': ans1.get('answer_id', ans1['question_id']),
|
104 |
+
'answer2_id': ans2.get('answer_id', ans2['answer_id']),
|
105 |
+
'category': category
|
106 |
+
}
|
107 |
+
if idx >= len(cur_reviews):
|
108 |
+
review = get_eval(content, args.max_tokens)
|
109 |
+
scores = parse_score(review)
|
110 |
+
cur_js['content'] = review
|
111 |
+
cur_js['tuple'] = scores
|
112 |
+
review_file.write(json.dumps(cur_js) + '\n')
|
113 |
+
review_file.flush()
|
114 |
+
else:
|
115 |
+
print(f'Skipping {idx} as we already have it.')
|
116 |
+
idx += 1
|
117 |
+
print(idx)
|
118 |
+
review_file.close()
|
llava/eval/eval_pope.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import argparse
|
4 |
+
|
5 |
+
def eval_pope(answers, label_file):
|
6 |
+
label_list = [json.loads(q)['label'] for q in open(label_file, 'r')]
|
7 |
+
|
8 |
+
for answer in answers:
|
9 |
+
text = answer['text']
|
10 |
+
|
11 |
+
# Only keep the first sentence
|
12 |
+
if text.find('.') != -1:
|
13 |
+
text = text.split('.')[0]
|
14 |
+
|
15 |
+
text = text.replace(',', '')
|
16 |
+
words = text.split(' ')
|
17 |
+
if 'No' in words or 'not' in words or 'no' in words:
|
18 |
+
answer['text'] = 'no'
|
19 |
+
else:
|
20 |
+
answer['text'] = 'yes'
|
21 |
+
|
22 |
+
for i in range(len(label_list)):
|
23 |
+
if label_list[i] == 'no':
|
24 |
+
label_list[i] = 0
|
25 |
+
else:
|
26 |
+
label_list[i] = 1
|
27 |
+
|
28 |
+
pred_list = []
|
29 |
+
for answer in answers:
|
30 |
+
if answer['text'] == 'no':
|
31 |
+
pred_list.append(0)
|
32 |
+
else:
|
33 |
+
pred_list.append(1)
|
34 |
+
|
35 |
+
pos = 1
|
36 |
+
neg = 0
|
37 |
+
yes_ratio = pred_list.count(1) / len(pred_list)
|
38 |
+
|
39 |
+
TP, TN, FP, FN = 0, 0, 0, 0
|
40 |
+
for pred, label in zip(pred_list, label_list):
|
41 |
+
if pred == pos and label == pos:
|
42 |
+
TP += 1
|
43 |
+
elif pred == pos and label == neg:
|
44 |
+
FP += 1
|
45 |
+
elif pred == neg and label == neg:
|
46 |
+
TN += 1
|
47 |
+
elif pred == neg and label == pos:
|
48 |
+
FN += 1
|
49 |
+
|
50 |
+
print('TP\tFP\tTN\tFN\t')
|
51 |
+
print('{}\t{}\t{}\t{}'.format(TP, FP, TN, FN))
|
52 |
+
|
53 |
+
precision = float(TP) / float(TP + FP)
|
54 |
+
recall = float(TP) / float(TP + FN)
|
55 |
+
f1 = 2*precision*recall / (precision + recall)
|
56 |
+
acc = (TP + TN) / (TP + TN + FP + FN)
|
57 |
+
print('Accuracy: {}'.format(acc))
|
58 |
+
print('Precision: {}'.format(precision))
|
59 |
+
print('Recall: {}'.format(recall))
|
60 |
+
print('F1 score: {}'.format(f1))
|
61 |
+
print('Yes ratio: {}'.format(yes_ratio))
|
62 |
+
print('%.3f, %.3f, %.3f, %.3f, %.3f' % (f1, acc, precision, recall, yes_ratio) )
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
parser = argparse.ArgumentParser()
|
66 |
+
parser.add_argument("--annotation-dir", type=str)
|
67 |
+
parser.add_argument("--question-file", type=str)
|
68 |
+
parser.add_argument("--result-file", type=str)
|
69 |
+
args = parser.parse_args()
|
70 |
+
|
71 |
+
questions = [json.loads(line) for line in open(args.question_file)]
|
72 |
+
questions = {question['question_id']: question for question in questions}
|
73 |
+
answers = [json.loads(q) for q in open(args.result_file)]
|
74 |
+
for file in os.listdir(args.annotation_dir):
|
75 |
+
assert file.startswith('coco_pope_')
|
76 |
+
assert file.endswith('.json')
|
77 |
+
category = file[10:-5]
|
78 |
+
cur_answers = [x for x in answers if questions[x['question_id']]['category'] == category]
|
79 |
+
print('Category: {}, # samples: {}'.format(category, len(cur_answers)))
|
80 |
+
eval_pope(cur_answers, os.path.join(args.annotation_dir, file))
|
81 |
+
print("====================================")
|
llava/eval/eval_science_qa.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import random
|
6 |
+
|
7 |
+
|
8 |
+
def get_args():
|
9 |
+
parser = argparse.ArgumentParser()
|
10 |
+
parser.add_argument('--base-dir', type=str)
|
11 |
+
parser.add_argument('--result-file', type=str)
|
12 |
+
parser.add_argument('--output-file', type=str)
|
13 |
+
parser.add_argument('--output-result', type=str)
|
14 |
+
parser.add_argument('--split', type=str, default='test')
|
15 |
+
parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
|
16 |
+
return parser.parse_args()
|
17 |
+
|
18 |
+
|
19 |
+
def convert_caps(results):
|
20 |
+
fakecaps = []
|
21 |
+
for result in results:
|
22 |
+
image_id = result['question_id']
|
23 |
+
caption = result['text']
|
24 |
+
fakecaps.append({"image_id": int(image_id), "caption": caption})
|
25 |
+
return fakecaps
|
26 |
+
|
27 |
+
|
28 |
+
def get_pred_idx(prediction, choices, options):
|
29 |
+
"""
|
30 |
+
Get the index (e.g. 2) from the prediction (e.g. 'C')
|
31 |
+
"""
|
32 |
+
if prediction in options[:len(choices)]:
|
33 |
+
return options.index(prediction)
|
34 |
+
else:
|
35 |
+
return random.choice(range(len(choices)))
|
36 |
+
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
args = get_args()
|
40 |
+
|
41 |
+
base_dir = args.base_dir
|
42 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
|
43 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
44 |
+
predictions = [json.loads(line) for line in open(args.result_file)]
|
45 |
+
predictions = {pred['question_id']: pred for pred in predictions}
|
46 |
+
split_problems = {idx: problems[idx] for idx in split_indices}
|
47 |
+
|
48 |
+
results = {'correct': [], 'incorrect': []}
|
49 |
+
sqa_results = {}
|
50 |
+
sqa_results['acc'] = None
|
51 |
+
sqa_results['correct'] = None
|
52 |
+
sqa_results['count'] = None
|
53 |
+
sqa_results['results'] = {}
|
54 |
+
sqa_results['outputs'] = {}
|
55 |
+
|
56 |
+
for prob_id, prob in split_problems.items():
|
57 |
+
if prob_id not in predictions:
|
58 |
+
continue
|
59 |
+
pred = predictions[prob_id]
|
60 |
+
pred_text = pred['text']
|
61 |
+
|
62 |
+
pattern = re.compile(r'The answer is ([A-Z]).')
|
63 |
+
res = pattern.findall(pred_text)
|
64 |
+
if len(res) == 1:
|
65 |
+
answer = res[0] # 'A', 'B', ...
|
66 |
+
else:
|
67 |
+
answer = "FAILED"
|
68 |
+
|
69 |
+
pred_idx = get_pred_idx(answer, prob['choices'], args.options)
|
70 |
+
|
71 |
+
analysis = {
|
72 |
+
'question_id': prob_id,
|
73 |
+
'parsed_ans': answer,
|
74 |
+
'ground_truth': args.options[prob['answer']],
|
75 |
+
'question': pred['prompt'],
|
76 |
+
'pred': pred_text,
|
77 |
+
'is_multimodal': '<image>' in pred['prompt'],
|
78 |
+
}
|
79 |
+
|
80 |
+
sqa_results['results'][prob_id] = get_pred_idx(answer, prob['choices'], args.options)
|
81 |
+
sqa_results['outputs'][prob_id] = pred_text
|
82 |
+
|
83 |
+
if pred_idx == prob['answer']:
|
84 |
+
results['correct'].append(analysis)
|
85 |
+
else:
|
86 |
+
results['incorrect'].append(analysis)
|
87 |
+
|
88 |
+
correct = len(results['correct'])
|
89 |
+
total = len(results['correct']) + len(results['incorrect'])
|
90 |
+
print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%')
|
91 |
+
|
92 |
+
sqa_results['acc'] = correct / total * 100
|
93 |
+
sqa_results['correct'] = correct
|
94 |
+
sqa_results['count'] = total
|
95 |
+
|
96 |
+
with open(args.output_file, 'w') as f:
|
97 |
+
json.dump(results, f, indent=2)
|
98 |
+
with open(args.output_result, 'w') as f:
|
99 |
+
json.dump(sqa_results, f, indent=2)
|
llava/eval/eval_science_qa_gpt4.py
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import random
|
6 |
+
from collections import defaultdict
|
7 |
+
|
8 |
+
|
9 |
+
def get_args():
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument('--base-dir', type=str)
|
12 |
+
parser.add_argument('--gpt4-result', type=str)
|
13 |
+
parser.add_argument('--our-result', type=str)
|
14 |
+
parser.add_argument('--split', type=str, default='test')
|
15 |
+
parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
|
16 |
+
return parser.parse_args()
|
17 |
+
|
18 |
+
|
19 |
+
def convert_caps(results):
|
20 |
+
fakecaps = []
|
21 |
+
for result in results:
|
22 |
+
image_id = result['question_id']
|
23 |
+
caption = result['text']
|
24 |
+
fakecaps.append({"image_id": int(image_id), "caption": caption})
|
25 |
+
return fakecaps
|
26 |
+
|
27 |
+
|
28 |
+
def get_pred_idx(prediction, choices, options):
|
29 |
+
"""
|
30 |
+
Get the index (e.g. 2) from the prediction (e.g. 'C')
|
31 |
+
"""
|
32 |
+
if prediction in options[:len(choices)]:
|
33 |
+
return options.index(prediction)
|
34 |
+
else:
|
35 |
+
return random.choice(range(len(choices)))
|
36 |
+
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
args = get_args()
|
40 |
+
|
41 |
+
base_dir = args.base_dir
|
42 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
|
43 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
44 |
+
our_predictions = [json.loads(line) for line in open(args.our_result)]
|
45 |
+
our_predictions = {pred['question_id']: pred for pred in our_predictions}
|
46 |
+
split_problems = {idx: problems[idx] for idx in split_indices}
|
47 |
+
|
48 |
+
gpt4_predictions = json.load(open(args.gpt4_result))['outputs']
|
49 |
+
|
50 |
+
results = defaultdict(lambda: 0)
|
51 |
+
|
52 |
+
for prob_id, prob in split_problems.items():
|
53 |
+
if prob_id not in our_predictions:
|
54 |
+
continue
|
55 |
+
if prob_id not in gpt4_predictions:
|
56 |
+
continue
|
57 |
+
our_pred = our_predictions[prob_id]['text']
|
58 |
+
gpt4_pred = gpt4_predictions[prob_id]
|
59 |
+
|
60 |
+
pattern = re.compile(r'The answer is ([A-Z]).')
|
61 |
+
our_res = pattern.findall(our_pred)
|
62 |
+
if len(our_res) == 1:
|
63 |
+
our_answer = our_res[0] # 'A', 'B', ...
|
64 |
+
else:
|
65 |
+
our_answer = "FAILED"
|
66 |
+
gpt4_res = pattern.findall(gpt4_pred)
|
67 |
+
if len(gpt4_res) == 1:
|
68 |
+
gpt4_answer = gpt4_res[0] # 'A', 'B', ...
|
69 |
+
else:
|
70 |
+
gpt4_answer = "FAILED"
|
71 |
+
|
72 |
+
our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options)
|
73 |
+
gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options)
|
74 |
+
|
75 |
+
if gpt4_answer == 'FAILED':
|
76 |
+
results['gpt4_failed'] += 1
|
77 |
+
# continue
|
78 |
+
gpt4_pred_idx = our_pred_idx
|
79 |
+
# if our_pred_idx != prob['answer']:
|
80 |
+
# print(our_predictions[prob_id]['prompt'])
|
81 |
+
# print('-----------------')
|
82 |
+
# print(f'LECTURE: {prob["lecture"]}')
|
83 |
+
# print(f'SOLUTION: {prob["solution"]}')
|
84 |
+
# print('=====================')
|
85 |
+
else:
|
86 |
+
# continue
|
87 |
+
pass
|
88 |
+
# gpt4_pred_idx = our_pred_idx
|
89 |
+
|
90 |
+
if gpt4_pred_idx == prob['answer']:
|
91 |
+
results['correct'] += 1
|
92 |
+
else:
|
93 |
+
results['incorrect'] += 1
|
94 |
+
|
95 |
+
|
96 |
+
if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']:
|
97 |
+
results['correct_upperbound'] += 1
|
98 |
+
|
99 |
+
correct = results['correct']
|
100 |
+
total = results['correct'] + results['incorrect']
|
101 |
+
print(f'Total: {total}, Correct: {correct}, Accuracy: {correct / total * 100:.2f}%')
|
102 |
+
print(f'Total: {total}, Correct (upper): {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%')
|
103 |
+
print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%')
|
104 |
+
|
llava/eval/eval_science_qa_gpt4_requery.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import random
|
6 |
+
from collections import defaultdict
|
7 |
+
|
8 |
+
|
9 |
+
def get_args():
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument('--base-dir', type=str)
|
12 |
+
parser.add_argument('--gpt4-result', type=str)
|
13 |
+
parser.add_argument('--requery-result', type=str)
|
14 |
+
parser.add_argument('--our-result', type=str)
|
15 |
+
parser.add_argument('--output-result', type=str)
|
16 |
+
parser.add_argument('--split', type=str, default='test')
|
17 |
+
parser.add_argument('--options', type=list, default=["A", "B", "C", "D", "E"])
|
18 |
+
return parser.parse_args()
|
19 |
+
|
20 |
+
|
21 |
+
def convert_caps(results):
|
22 |
+
fakecaps = []
|
23 |
+
for result in results:
|
24 |
+
image_id = result['question_id']
|
25 |
+
caption = result['text']
|
26 |
+
fakecaps.append({"image_id": int(image_id), "caption": caption})
|
27 |
+
return fakecaps
|
28 |
+
|
29 |
+
|
30 |
+
def get_pred_idx(prediction, choices, options):
|
31 |
+
"""
|
32 |
+
Get the index (e.g. 2) from the prediction (e.g. 'C')
|
33 |
+
"""
|
34 |
+
if prediction in options[:len(choices)]:
|
35 |
+
return options.index(prediction)
|
36 |
+
else:
|
37 |
+
return random.choice(range(len(choices)))
|
38 |
+
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
args = get_args()
|
42 |
+
|
43 |
+
base_dir = args.base_dir
|
44 |
+
split_indices = json.load(open(os.path.join(base_dir, "pid_splits.json")))[args.split]
|
45 |
+
problems = json.load(open(os.path.join(base_dir, "problems.json")))
|
46 |
+
our_predictions = [json.loads(line) for line in open(args.our_result)]
|
47 |
+
our_predictions = {pred['question_id']: pred for pred in our_predictions}
|
48 |
+
split_problems = {idx: problems[idx] for idx in split_indices}
|
49 |
+
|
50 |
+
requery_predictions = [json.loads(line) for line in open(args.requery_result)]
|
51 |
+
requery_predictions = {pred['question_id']: pred for pred in requery_predictions}
|
52 |
+
|
53 |
+
gpt4_predictions = json.load(open(args.gpt4_result))['outputs']
|
54 |
+
|
55 |
+
results = defaultdict(lambda: 0)
|
56 |
+
|
57 |
+
sqa_results = {}
|
58 |
+
sqa_results['acc'] = None
|
59 |
+
sqa_results['correct'] = None
|
60 |
+
sqa_results['count'] = None
|
61 |
+
sqa_results['results'] = {}
|
62 |
+
sqa_results['outputs'] = {}
|
63 |
+
|
64 |
+
for prob_id, prob in split_problems.items():
|
65 |
+
if prob_id not in our_predictions:
|
66 |
+
assert False
|
67 |
+
if prob_id not in gpt4_predictions:
|
68 |
+
assert False
|
69 |
+
our_pred = our_predictions[prob_id]['text']
|
70 |
+
gpt4_pred = gpt4_predictions[prob_id]
|
71 |
+
if prob_id not in requery_predictions:
|
72 |
+
results['missing_requery'] += 1
|
73 |
+
requery_pred = "MISSING"
|
74 |
+
else:
|
75 |
+
requery_pred = requery_predictions[prob_id]['text']
|
76 |
+
|
77 |
+
pattern = re.compile(r'The answer is ([A-Z]).')
|
78 |
+
our_res = pattern.findall(our_pred)
|
79 |
+
if len(our_res) == 1:
|
80 |
+
our_answer = our_res[0] # 'A', 'B', ...
|
81 |
+
else:
|
82 |
+
our_answer = "FAILED"
|
83 |
+
|
84 |
+
requery_res = pattern.findall(requery_pred)
|
85 |
+
if len(requery_res) == 1:
|
86 |
+
requery_answer = requery_res[0] # 'A', 'B', ...
|
87 |
+
else:
|
88 |
+
requery_answer = "FAILED"
|
89 |
+
|
90 |
+
gpt4_res = pattern.findall(gpt4_pred)
|
91 |
+
if len(gpt4_res) == 1:
|
92 |
+
gpt4_answer = gpt4_res[0] # 'A', 'B', ...
|
93 |
+
else:
|
94 |
+
gpt4_answer = "FAILED"
|
95 |
+
|
96 |
+
our_pred_idx = get_pred_idx(our_answer, prob['choices'], args.options)
|
97 |
+
gpt4_pred_idx = get_pred_idx(gpt4_answer, prob['choices'], args.options)
|
98 |
+
requery_pred_idx = get_pred_idx(requery_answer, prob['choices'], args.options)
|
99 |
+
|
100 |
+
results['total'] += 1
|
101 |
+
|
102 |
+
if gpt4_answer == 'FAILED':
|
103 |
+
results['gpt4_failed'] += 1
|
104 |
+
if gpt4_pred_idx == prob['answer']:
|
105 |
+
results['gpt4_correct'] += 1
|
106 |
+
if our_pred_idx == prob['answer']:
|
107 |
+
results['gpt4_ourvisual_correct'] += 1
|
108 |
+
elif gpt4_pred_idx == prob['answer']:
|
109 |
+
results['gpt4_correct'] += 1
|
110 |
+
results['gpt4_ourvisual_correct'] += 1
|
111 |
+
|
112 |
+
if our_pred_idx == prob['answer']:
|
113 |
+
results['our_correct'] += 1
|
114 |
+
|
115 |
+
if requery_answer == 'FAILED':
|
116 |
+
sqa_results['results'][prob_id] = our_pred_idx
|
117 |
+
if our_pred_idx == prob['answer']:
|
118 |
+
results['requery_correct'] += 1
|
119 |
+
else:
|
120 |
+
sqa_results['results'][prob_id] = requery_pred_idx
|
121 |
+
if requery_pred_idx == prob['answer']:
|
122 |
+
results['requery_correct'] += 1
|
123 |
+
else:
|
124 |
+
print(f"""
|
125 |
+
Question ({args.options[prob['answer']]}): {our_predictions[prob_id]['prompt']}
|
126 |
+
Our ({our_answer}): {our_pred}
|
127 |
+
GPT-4 ({gpt4_answer}): {gpt4_pred}
|
128 |
+
Requery ({requery_answer}): {requery_pred}
|
129 |
+
print("=====================================")
|
130 |
+
""")
|
131 |
+
|
132 |
+
if gpt4_pred_idx == prob['answer'] or our_pred_idx == prob['answer']:
|
133 |
+
results['correct_upperbound'] += 1
|
134 |
+
|
135 |
+
total = results['total']
|
136 |
+
print(f'Total: {total}, Our-Correct: {results["our_correct"]}, Accuracy: {results["our_correct"] / total * 100:.2f}%')
|
137 |
+
print(f'Total: {total}, GPT-4-Correct: {results["gpt4_correct"]}, Accuracy: {results["gpt4_correct"] / total * 100:.2f}%')
|
138 |
+
print(f'Total: {total}, GPT-4 NO-ANS (RANDOM): {results["gpt4_failed"]}, Percentage: {results["gpt4_failed"] / total * 100:.2f}%')
|
139 |
+
print(f'Total: {total}, GPT-4-OursVisual-Correct: {results["gpt4_ourvisual_correct"]}, Accuracy: {results["gpt4_ourvisual_correct"] / total * 100:.2f}%')
|
140 |
+
print(f'Total: {total}, Requery-Correct: {results["requery_correct"]}, Accuracy: {results["requery_correct"] / total * 100:.2f}%')
|
141 |
+
print(f'Total: {total}, Correct upper: {results["correct_upperbound"]}, Accuracy: {results["correct_upperbound"] / total * 100:.2f}%')
|
142 |
+
|
143 |
+
sqa_results['acc'] = results["requery_correct"] / total * 100
|
144 |
+
sqa_results['correct'] = results["requery_correct"]
|
145 |
+
sqa_results['count'] = total
|
146 |
+
|
147 |
+
with open(args.output_result, 'w') as f:
|
148 |
+
json.dump(sqa_results, f, indent=2)
|
149 |
+
|
llava/eval/eval_textvqa.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import re
|
5 |
+
|
6 |
+
from llava.eval.m4c_evaluator import TextVQAAccuracyEvaluator
|
7 |
+
|
8 |
+
|
9 |
+
def get_args():
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument('--annotation-file', type=str)
|
12 |
+
parser.add_argument('--result-file', type=str)
|
13 |
+
parser.add_argument('--result-dir', type=str)
|
14 |
+
return parser.parse_args()
|
15 |
+
|
16 |
+
|
17 |
+
def prompt_processor(prompt):
|
18 |
+
if prompt.startswith('OCR tokens: '):
|
19 |
+
pattern = r"Question: (.*?) Short answer:"
|
20 |
+
match = re.search(pattern, prompt, re.DOTALL)
|
21 |
+
question = match.group(1)
|
22 |
+
elif 'Reference OCR token: ' in prompt and len(prompt.split('\n')) == 3:
|
23 |
+
if prompt.startswith('Reference OCR token:'):
|
24 |
+
question = prompt.split('\n')[1]
|
25 |
+
else:
|
26 |
+
question = prompt.split('\n')[0]
|
27 |
+
elif len(prompt.split('\n')) == 2:
|
28 |
+
question = prompt.split('\n')[0]
|
29 |
+
else:
|
30 |
+
assert False
|
31 |
+
|
32 |
+
return question.lower()
|
33 |
+
|
34 |
+
|
35 |
+
def eval_single(annotation_file, result_file):
|
36 |
+
experiment_name = os.path.splitext(os.path.basename(result_file))[0]
|
37 |
+
print(experiment_name)
|
38 |
+
annotations = json.load(open(annotation_file))['data']
|
39 |
+
annotations = {(annotation['image_id'], annotation['question'].lower()): annotation for annotation in annotations}
|
40 |
+
results = [json.loads(line) for line in open(result_file)]
|
41 |
+
|
42 |
+
pred_list = []
|
43 |
+
for result in results:
|
44 |
+
annotation = annotations[(result['question_id'], prompt_processor(result['prompt']))]
|
45 |
+
pred_list.append({
|
46 |
+
"pred_answer": result['text'],
|
47 |
+
"gt_answers": annotation['answers'],
|
48 |
+
})
|
49 |
+
|
50 |
+
evaluator = TextVQAAccuracyEvaluator()
|
51 |
+
print('Samples: {}\nAccuracy: {:.2f}%\n'.format(len(pred_list), 100. * evaluator.eval_pred_list(pred_list)))
|
52 |
+
|
53 |
+
|
54 |
+
if __name__ == "__main__":
|
55 |
+
args = get_args()
|
56 |
+
|
57 |
+
if args.result_file is not None:
|
58 |
+
eval_single(args.annotation_file, args.result_file)
|
59 |
+
|
60 |
+
if args.result_dir is not None:
|
61 |
+
for result_file in sorted(os.listdir(args.result_dir)):
|
62 |
+
if not result_file.endswith('.jsonl'):
|
63 |
+
print(f'Skipping {result_file}')
|
64 |
+
continue
|
65 |
+
eval_single(args.annotation_file, os.path.join(args.result_dir, result_file))
|
llava/eval/generate_webpage_data_from_table.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Generate json file for webpage."""
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
|
6 |
+
# models = ['llama', 'alpaca', 'gpt35', 'bard']
|
7 |
+
models = ['vicuna']
|
8 |
+
|
9 |
+
|
10 |
+
def read_jsonl(path: str, key: str=None):
|
11 |
+
data = []
|
12 |
+
with open(os.path.expanduser(path)) as f:
|
13 |
+
for line in f:
|
14 |
+
if not line:
|
15 |
+
continue
|
16 |
+
data.append(json.loads(line))
|
17 |
+
if key is not None:
|
18 |
+
data.sort(key=lambda x: x[key])
|
19 |
+
data = {item[key]: item for item in data}
|
20 |
+
return data
|
21 |
+
|
22 |
+
|
23 |
+
def trim_hanging_lines(s: str, n: int) -> str:
|
24 |
+
s = s.strip()
|
25 |
+
for _ in range(n):
|
26 |
+
s = s.split('\n', 1)[1].strip()
|
27 |
+
return s
|
28 |
+
|
29 |
+
|
30 |
+
if __name__ == '__main__':
|
31 |
+
questions = read_jsonl('table/question.jsonl', key='question_id')
|
32 |
+
|
33 |
+
# alpaca_answers = read_jsonl('table/answer/answer_alpaca-13b.jsonl', key='question_id')
|
34 |
+
# bard_answers = read_jsonl('table/answer/answer_bard.jsonl', key='question_id')
|
35 |
+
# gpt35_answers = read_jsonl('table/answer/answer_gpt35.jsonl', key='question_id')
|
36 |
+
# llama_answers = read_jsonl('table/answer/answer_llama-13b.jsonl', key='question_id')
|
37 |
+
vicuna_answers = read_jsonl('table/answer/answer_vicuna-13b.jsonl', key='question_id')
|
38 |
+
ours_answers = read_jsonl('table/results/llama-13b-hf-alpaca.jsonl', key='question_id')
|
39 |
+
|
40 |
+
review_vicuna = read_jsonl('table/review/review_vicuna-13b_llama-13b-hf-alpaca.jsonl', key='question_id')
|
41 |
+
# review_alpaca = read_jsonl('table/review/review_alpaca-13b_vicuna-13b.jsonl', key='question_id')
|
42 |
+
# review_bard = read_jsonl('table/review/review_bard_vicuna-13b.jsonl', key='question_id')
|
43 |
+
# review_gpt35 = read_jsonl('table/review/review_gpt35_vicuna-13b.jsonl', key='question_id')
|
44 |
+
# review_llama = read_jsonl('table/review/review_llama-13b_vicuna-13b.jsonl', key='question_id')
|
45 |
+
|
46 |
+
records = []
|
47 |
+
for qid in questions.keys():
|
48 |
+
r = {
|
49 |
+
'id': qid,
|
50 |
+
'category': questions[qid]['category'],
|
51 |
+
'question': questions[qid]['text'],
|
52 |
+
'answers': {
|
53 |
+
# 'alpaca': alpaca_answers[qid]['text'],
|
54 |
+
# 'llama': llama_answers[qid]['text'],
|
55 |
+
# 'bard': bard_answers[qid]['text'],
|
56 |
+
# 'gpt35': gpt35_answers[qid]['text'],
|
57 |
+
'vicuna': vicuna_answers[qid]['text'],
|
58 |
+
'ours': ours_answers[qid]['text'],
|
59 |
+
},
|
60 |
+
'evaluations': {
|
61 |
+
# 'alpaca': review_alpaca[qid]['text'],
|
62 |
+
# 'llama': review_llama[qid]['text'],
|
63 |
+
# 'bard': review_bard[qid]['text'],
|
64 |
+
'vicuna': review_vicuna[qid]['content'],
|
65 |
+
# 'gpt35': review_gpt35[qid]['text'],
|
66 |
+
},
|
67 |
+
'scores': {
|
68 |
+
'vicuna': review_vicuna[qid]['tuple'],
|
69 |
+
# 'alpaca': review_alpaca[qid]['score'],
|
70 |
+
# 'llama': review_llama[qid]['score'],
|
71 |
+
# 'bard': review_bard[qid]['score'],
|
72 |
+
# 'gpt35': review_gpt35[qid]['score'],
|
73 |
+
},
|
74 |
+
}
|
75 |
+
|
76 |
+
# cleanup data
|
77 |
+
cleaned_evals = {}
|
78 |
+
for k, v in r['evaluations'].items():
|
79 |
+
v = v.strip()
|
80 |
+
lines = v.split('\n')
|
81 |
+
# trim the first line if it's a pair of numbers
|
82 |
+
if re.match(r'\d+[, ]+\d+', lines[0]):
|
83 |
+
lines = lines[1:]
|
84 |
+
v = '\n'.join(lines)
|
85 |
+
cleaned_evals[k] = v.replace('Assistant 1', "**Assistant 1**").replace('Assistant 2', '**Assistant 2**')
|
86 |
+
|
87 |
+
r['evaluations'] = cleaned_evals
|
88 |
+
records.append(r)
|
89 |
+
|
90 |
+
# Reorder the records, this is optional
|
91 |
+
for r in records:
|
92 |
+
if r['id'] <= 20:
|
93 |
+
r['id'] += 60
|
94 |
+
else:
|
95 |
+
r['id'] -= 20
|
96 |
+
for r in records:
|
97 |
+
if r['id'] <= 50:
|
98 |
+
r['id'] += 10
|
99 |
+
elif 50 < r['id'] <= 60:
|
100 |
+
r['id'] -= 50
|
101 |
+
for r in records:
|
102 |
+
if r['id'] == 7:
|
103 |
+
r['id'] = 1
|
104 |
+
elif r['id'] < 7:
|
105 |
+
r['id'] += 1
|
106 |
+
|
107 |
+
records.sort(key=lambda x: x['id'])
|
108 |
+
|
109 |
+
# Write to file
|
110 |
+
with open('webpage/data.json', 'w') as f:
|
111 |
+
json.dump({'questions': records, 'models': models}, f, indent=2)
|
llava/eval/m4c_evaluator.py
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
+
import re
|
3 |
+
|
4 |
+
from tqdm import tqdm
|
5 |
+
|
6 |
+
|
7 |
+
class EvalAIAnswerProcessor:
|
8 |
+
"""
|
9 |
+
Processes an answer similar to Eval AI
|
10 |
+
copied from
|
11 |
+
https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897
|
12 |
+
"""
|
13 |
+
|
14 |
+
CONTRACTIONS = {
|
15 |
+
"aint": "ain't",
|
16 |
+
"arent": "aren't",
|
17 |
+
"cant": "can't",
|
18 |
+
"couldve": "could've",
|
19 |
+
"couldnt": "couldn't",
|
20 |
+
"couldn'tve": "couldn't've",
|
21 |
+
"couldnt've": "couldn't've",
|
22 |
+
"didnt": "didn't",
|
23 |
+
"doesnt": "doesn't",
|
24 |
+
"dont": "don't",
|
25 |
+
"hadnt": "hadn't",
|
26 |
+
"hadnt've": "hadn't've",
|
27 |
+
"hadn'tve": "hadn't've",
|
28 |
+
"hasnt": "hasn't",
|
29 |
+
"havent": "haven't",
|
30 |
+
"hed": "he'd",
|
31 |
+
"hed've": "he'd've",
|
32 |
+
"he'dve": "he'd've",
|
33 |
+
"hes": "he's",
|
34 |
+
"howd": "how'd",
|
35 |
+
"howll": "how'll",
|
36 |
+
"hows": "how's",
|
37 |
+
"Id've": "I'd've",
|
38 |
+
"I'dve": "I'd've",
|
39 |
+
"Im": "I'm",
|
40 |
+
"Ive": "I've",
|
41 |
+
"isnt": "isn't",
|
42 |
+
"itd": "it'd",
|
43 |
+
"itd've": "it'd've",
|
44 |
+
"it'dve": "it'd've",
|
45 |
+
"itll": "it'll",
|
46 |
+
"let's": "let's",
|
47 |
+
"maam": "ma'am",
|
48 |
+
"mightnt": "mightn't",
|
49 |
+
"mightnt've": "mightn't've",
|
50 |
+
"mightn'tve": "mightn't've",
|
51 |
+
"mightve": "might've",
|
52 |
+
"mustnt": "mustn't",
|
53 |
+
"mustve": "must've",
|
54 |
+
"neednt": "needn't",
|
55 |
+
"notve": "not've",
|
56 |
+
"oclock": "o'clock",
|
57 |
+
"oughtnt": "oughtn't",
|
58 |
+
"ow's'at": "'ow's'at",
|
59 |
+
"'ows'at": "'ow's'at",
|
60 |
+
"'ow'sat": "'ow's'at",
|
61 |
+
"shant": "shan't",
|
62 |
+
"shed've": "she'd've",
|
63 |
+
"she'dve": "she'd've",
|
64 |
+
"she's": "she's",
|
65 |
+
"shouldve": "should've",
|
66 |
+
"shouldnt": "shouldn't",
|
67 |
+
"shouldnt've": "shouldn't've",
|
68 |
+
"shouldn'tve": "shouldn't've",
|
69 |
+
"somebody'd": "somebodyd",
|
70 |
+
"somebodyd've": "somebody'd've",
|
71 |
+
"somebody'dve": "somebody'd've",
|
72 |
+
"somebodyll": "somebody'll",
|
73 |
+
"somebodys": "somebody's",
|
74 |
+
"someoned": "someone'd",
|
75 |
+
"someoned've": "someone'd've",
|
76 |
+
"someone'dve": "someone'd've",
|
77 |
+
"someonell": "someone'll",
|
78 |
+
"someones": "someone's",
|
79 |
+
"somethingd": "something'd",
|
80 |
+
"somethingd've": "something'd've",
|
81 |
+
"something'dve": "something'd've",
|
82 |
+
"somethingll": "something'll",
|
83 |
+
"thats": "that's",
|
84 |
+
"thered": "there'd",
|
85 |
+
"thered've": "there'd've",
|
86 |
+
"there'dve": "there'd've",
|
87 |
+
"therere": "there're",
|
88 |
+
"theres": "there's",
|
89 |
+
"theyd": "they'd",
|
90 |
+
"theyd've": "they'd've",
|
91 |
+
"they'dve": "they'd've",
|
92 |
+
"theyll": "they'll",
|
93 |
+
"theyre": "they're",
|
94 |
+
"theyve": "they've",
|
95 |
+
"twas": "'twas",
|
96 |
+
"wasnt": "wasn't",
|
97 |
+
"wed've": "we'd've",
|
98 |
+
"we'dve": "we'd've",
|
99 |
+
"weve": "we've",
|
100 |
+
"werent": "weren't",
|
101 |
+
"whatll": "what'll",
|
102 |
+
"whatre": "what're",
|
103 |
+
"whats": "what's",
|
104 |
+
"whatve": "what've",
|
105 |
+
"whens": "when's",
|
106 |
+
"whered": "where'd",
|
107 |
+
"wheres": "where's",
|
108 |
+
"whereve": "where've",
|
109 |
+
"whod": "who'd",
|
110 |
+
"whod've": "who'd've",
|
111 |
+
"who'dve": "who'd've",
|
112 |
+
"wholl": "who'll",
|
113 |
+
"whos": "who's",
|
114 |
+
"whove": "who've",
|
115 |
+
"whyll": "why'll",
|
116 |
+
"whyre": "why're",
|
117 |
+
"whys": "why's",
|
118 |
+
"wont": "won't",
|
119 |
+
"wouldve": "would've",
|
120 |
+
"wouldnt": "wouldn't",
|
121 |
+
"wouldnt've": "wouldn't've",
|
122 |
+
"wouldn'tve": "wouldn't've",
|
123 |
+
"yall": "y'all",
|
124 |
+
"yall'll": "y'all'll",
|
125 |
+
"y'allll": "y'all'll",
|
126 |
+
"yall'd've": "y'all'd've",
|
127 |
+
"y'alld've": "y'all'd've",
|
128 |
+
"y'all'dve": "y'all'd've",
|
129 |
+
"youd": "you'd",
|
130 |
+
"youd've": "you'd've",
|
131 |
+
"you'dve": "you'd've",
|
132 |
+
"youll": "you'll",
|
133 |
+
"youre": "you're",
|
134 |
+
"youve": "you've",
|
135 |
+
}
|
136 |
+
|
137 |
+
NUMBER_MAP = {
|
138 |
+
"none": "0",
|
139 |
+
"zero": "0",
|
140 |
+
"one": "1",
|
141 |
+
"two": "2",
|
142 |
+
"three": "3",
|
143 |
+
"four": "4",
|
144 |
+
"five": "5",
|
145 |
+
"six": "6",
|
146 |
+
"seven": "7",
|
147 |
+
"eight": "8",
|
148 |
+
"nine": "9",
|
149 |
+
"ten": "10",
|
150 |
+
}
|
151 |
+
ARTICLES = ["a", "an", "the"]
|
152 |
+
PERIOD_STRIP = re.compile(r"(?!<=\d)(\.)(?!\d)")
|
153 |
+
COMMA_STRIP = re.compile(r"(?<=\d)(\,)+(?=\d)")
|
154 |
+
PUNCTUATIONS = [
|
155 |
+
";",
|
156 |
+
r"/",
|
157 |
+
"[",
|
158 |
+
"]",
|
159 |
+
'"',
|
160 |
+
"{",
|
161 |
+
"}",
|
162 |
+
"(",
|
163 |
+
")",
|
164 |
+
"=",
|
165 |
+
"+",
|
166 |
+
"\\",
|
167 |
+
"_",
|
168 |
+
"-",
|
169 |
+
">",
|
170 |
+
"<",
|
171 |
+
"@",
|
172 |
+
"`",
|
173 |
+
",",
|
174 |
+
"?",
|
175 |
+
"!",
|
176 |
+
]
|
177 |
+
|
178 |
+
def __init__(self, *args, **kwargs):
|
179 |
+
pass
|
180 |
+
|
181 |
+
def word_tokenize(self, word):
|
182 |
+
word = word.lower()
|
183 |
+
word = word.replace(",", "").replace("?", "").replace("'s", " 's")
|
184 |
+
return word.strip()
|
185 |
+
|
186 |
+
def process_punctuation(self, in_text):
|
187 |
+
out_text = in_text
|
188 |
+
for p in self.PUNCTUATIONS:
|
189 |
+
if (p + " " in in_text or " " + p in in_text) or (
|
190 |
+
re.search(self.COMMA_STRIP, in_text) is not None
|
191 |
+
):
|
192 |
+
out_text = out_text.replace(p, "")
|
193 |
+
else:
|
194 |
+
out_text = out_text.replace(p, " ")
|
195 |
+
out_text = self.PERIOD_STRIP.sub("", out_text, re.UNICODE)
|
196 |
+
return out_text
|
197 |
+
|
198 |
+
def process_digit_article(self, in_text):
|
199 |
+
out_text = []
|
200 |
+
temp_text = in_text.lower().split()
|
201 |
+
for word in temp_text:
|
202 |
+
word = self.NUMBER_MAP.setdefault(word, word)
|
203 |
+
if word not in self.ARTICLES:
|
204 |
+
out_text.append(word)
|
205 |
+
else:
|
206 |
+
pass
|
207 |
+
for word_id, word in enumerate(out_text):
|
208 |
+
if word in self.CONTRACTIONS:
|
209 |
+
out_text[word_id] = self.CONTRACTIONS[word]
|
210 |
+
out_text = " ".join(out_text)
|
211 |
+
return out_text
|
212 |
+
|
213 |
+
def __call__(self, item):
|
214 |
+
item = self.word_tokenize(item)
|
215 |
+
item = item.replace("\n", " ").replace("\t", " ").strip()
|
216 |
+
item = self.process_punctuation(item)
|
217 |
+
item = self.process_digit_article(item)
|
218 |
+
return item
|
219 |
+
|
220 |
+
|
221 |
+
class TextVQAAccuracyEvaluator:
|
222 |
+
def __init__(self):
|
223 |
+
self.answer_processor = EvalAIAnswerProcessor()
|
224 |
+
|
225 |
+
def _compute_answer_scores(self, raw_answers):
|
226 |
+
"""
|
227 |
+
compute the accuracy (soft score) of human answers
|
228 |
+
"""
|
229 |
+
answers = [self.answer_processor(a) for a in raw_answers]
|
230 |
+
assert len(answers) == 10
|
231 |
+
gt_answers = list(enumerate(answers))
|
232 |
+
unique_answers = set(answers)
|
233 |
+
unique_answer_scores = {}
|
234 |
+
|
235 |
+
for unique_answer in unique_answers:
|
236 |
+
accs = []
|
237 |
+
for gt_answer in gt_answers:
|
238 |
+
other_answers = [item for item in gt_answers if item != gt_answer]
|
239 |
+
matching_answers = [
|
240 |
+
item for item in other_answers if item[1] == unique_answer
|
241 |
+
]
|
242 |
+
acc = min(1, float(len(matching_answers)) / 3)
|
243 |
+
accs.append(acc)
|
244 |
+
unique_answer_scores[unique_answer] = sum(accs) / len(accs)
|
245 |
+
|
246 |
+
return unique_answer_scores
|
247 |
+
|
248 |
+
def eval_pred_list(self, pred_list):
|
249 |
+
pred_scores = []
|
250 |
+
for entry in tqdm(pred_list):
|
251 |
+
pred_answer = self.answer_processor(entry["pred_answer"])
|
252 |
+
unique_answer_scores = self._compute_answer_scores(entry["gt_answers"])
|
253 |
+
score = unique_answer_scores.get(pred_answer, 0.0)
|
254 |
+
pred_scores.append(score)
|
255 |
+
|
256 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
257 |
+
return accuracy
|
258 |
+
|
259 |
+
|
260 |
+
class STVQAAccuracyEvaluator:
|
261 |
+
def __init__(self):
|
262 |
+
self.answer_processor = EvalAIAnswerProcessor()
|
263 |
+
|
264 |
+
def eval_pred_list(self, pred_list):
|
265 |
+
pred_scores = []
|
266 |
+
for entry in pred_list:
|
267 |
+
pred_answer = self.answer_processor(entry["pred_answer"])
|
268 |
+
gts = [self.answer_processor(a) for a in entry["gt_answers"]]
|
269 |
+
score = 1.0 if pred_answer in gts else 0.0
|
270 |
+
pred_scores.append(score)
|
271 |
+
|
272 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
273 |
+
return accuracy
|
274 |
+
|
275 |
+
|
276 |
+
class STVQAANLSEvaluator:
|
277 |
+
def __init__(self):
|
278 |
+
import editdistance # install with `pip install editdistance`
|
279 |
+
|
280 |
+
self.get_edit_distance = editdistance.eval
|
281 |
+
|
282 |
+
def get_anls(self, s1, s2):
|
283 |
+
s1 = s1.lower().strip()
|
284 |
+
s2 = s2.lower().strip()
|
285 |
+
iou = 1 - self.get_edit_distance(s1, s2) / max(len(s1), len(s2))
|
286 |
+
anls = iou if iou >= 0.5 else 0.0
|
287 |
+
return anls
|
288 |
+
|
289 |
+
def eval_pred_list(self, pred_list):
|
290 |
+
pred_scores = []
|
291 |
+
for entry in pred_list:
|
292 |
+
anls = max(
|
293 |
+
self.get_anls(entry["pred_answer"], gt) for gt in entry["gt_answers"]
|
294 |
+
)
|
295 |
+
pred_scores.append(anls)
|
296 |
+
|
297 |
+
accuracy = sum(pred_scores) / len(pred_scores)
|
298 |
+
return accuracy
|
299 |
+
|
300 |
+
|
301 |
+
class TextCapsBleu4Evaluator:
|
302 |
+
def __init__(self):
|
303 |
+
# The following script requires Java 1.8.0 and pycocotools installed.
|
304 |
+
# The pycocoevalcap can be installed with pip as
|
305 |
+
# pip install git+https://github.com/ronghanghu/coco-caption.git@python23
|
306 |
+
# Original pycocoevalcap code is at https://github.com/tylin/coco-caption
|
307 |
+
# but has no python3 support yet.
|
308 |
+
try:
|
309 |
+
from pycocoevalcap.bleu.bleu import Bleu
|
310 |
+
from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
|
311 |
+
except ModuleNotFoundError:
|
312 |
+
print(
|
313 |
+
"Please install pycocoevalcap module using "
|
314 |
+
"pip install git+https://github.com/ronghanghu/coco-caption.git@python23" # noqa
|
315 |
+
)
|
316 |
+
raise
|
317 |
+
|
318 |
+
self.tokenizer = PTBTokenizer()
|
319 |
+
self.scorer = Bleu(4)
|
320 |
+
|
321 |
+
def eval_pred_list(self, pred_list):
|
322 |
+
# Create reference and hypotheses captions.
|
323 |
+
gts = {}
|
324 |
+
res = {}
|
325 |
+
for idx, entry in enumerate(pred_list):
|
326 |
+
gts[idx] = [{"caption": a} for a in entry["gt_answers"]]
|
327 |
+
res[idx] = [{"caption": entry["pred_answer"]}]
|
328 |
+
|
329 |
+
gts = self.tokenizer.tokenize(gts)
|
330 |
+
res = self.tokenizer.tokenize(res)
|
331 |
+
score, _ = self.scorer.compute_score(gts, res)
|
332 |
+
|
333 |
+
bleu4 = score[3] # score is (Bleu-1, Bleu-2, Bleu-3, Bleu-4)
|
334 |
+
return bleu4
|
llava/eval/model_captioning.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava.model.builder import load_pretrained_model
|
11 |
+
from llava.utils import disable_torch_init
|
12 |
+
from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
|
13 |
+
from torch.utils.data import Dataset, DataLoader
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import math
|
17 |
+
|
18 |
+
|
19 |
+
def split_list(lst, n):
|
20 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
21 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
22 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
23 |
+
|
24 |
+
|
25 |
+
def get_chunk(lst, n, k):
|
26 |
+
chunks = split_list(lst, n)
|
27 |
+
return chunks[k]
|
28 |
+
|
29 |
+
|
30 |
+
# Custom dataset class
|
31 |
+
class CustomDataset(Dataset):
|
32 |
+
def __init__(self, questions, image_folder, tokenizer, image_processor, model_config):
|
33 |
+
self.questions = questions
|
34 |
+
self.image_folder = image_folder
|
35 |
+
self.tokenizer = tokenizer
|
36 |
+
self.image_processor = image_processor
|
37 |
+
self.model_config = model_config
|
38 |
+
|
39 |
+
def __getitem__(self, index):
|
40 |
+
line = self.questions[index]
|
41 |
+
image_file = line["image"]
|
42 |
+
qs = line["text"]
|
43 |
+
if self.model_config.mm_use_im_start_end:
|
44 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
45 |
+
else:
|
46 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
47 |
+
|
48 |
+
conv = conv_templates[args.conv_mode].copy()
|
49 |
+
conv.append_message(conv.roles[0], qs)
|
50 |
+
conv.append_message(conv.roles[1], None)
|
51 |
+
prompt = conv.get_prompt()
|
52 |
+
|
53 |
+
image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
|
54 |
+
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
|
55 |
+
|
56 |
+
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
|
57 |
+
|
58 |
+
return input_ids, image_tensor
|
59 |
+
|
60 |
+
def __len__(self):
|
61 |
+
return len(self.questions)
|
62 |
+
|
63 |
+
|
64 |
+
# DataLoader
|
65 |
+
def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, batch_size=1, num_workers=4):
|
66 |
+
assert batch_size == 1, "batch_size must be 1"
|
67 |
+
dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config)
|
68 |
+
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
|
69 |
+
return data_loader
|
70 |
+
|
71 |
+
|
72 |
+
def eval_model(args):
|
73 |
+
# Model
|
74 |
+
disable_torch_init()
|
75 |
+
model_path = os.path.expanduser(args.model_path)
|
76 |
+
model_name = get_model_name_from_path(model_path)
|
77 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
78 |
+
|
79 |
+
questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
80 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
81 |
+
answers_file = os.path.expanduser(args.answers_file)
|
82 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
83 |
+
ans_file = open(answers_file, "w")
|
84 |
+
|
85 |
+
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
86 |
+
args.conv_mode = args.conv_mode + '_mmtag'
|
87 |
+
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
88 |
+
|
89 |
+
data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config)
|
90 |
+
|
91 |
+
for (input_ids, image_tensor), line in tqdm(zip(data_loader, questions), total=len(questions)):
|
92 |
+
idx = line["question_id"]
|
93 |
+
# cur_prompt = line["text"]
|
94 |
+
cur_prompt = "Describe with a short sentence"
|
95 |
+
|
96 |
+
stop_str = conv_templates[args.conv_mode].sep if conv_templates[args.conv_mode].sep_style != SeparatorStyle.TWO else conv_templates[args.conv_mode].sep2
|
97 |
+
input_ids = input_ids.to(device='cuda', non_blocking=True)
|
98 |
+
|
99 |
+
with torch.inference_mode():
|
100 |
+
output_ids = model.generate(
|
101 |
+
input_ids,
|
102 |
+
images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
|
103 |
+
do_sample=True if args.temperature > 0 else False,
|
104 |
+
temperature=args.temperature,
|
105 |
+
top_p=args.top_p,
|
106 |
+
num_beams=args.num_beams,
|
107 |
+
max_new_tokens=32,
|
108 |
+
use_cache=True)
|
109 |
+
|
110 |
+
input_token_len = input_ids.shape[1]
|
111 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
112 |
+
if n_diff_input_output > 0:
|
113 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
114 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
115 |
+
outputs = outputs.strip()
|
116 |
+
if outputs.endswith(stop_str):
|
117 |
+
outputs = outputs[:-len(stop_str)]
|
118 |
+
outputs = outputs.strip()
|
119 |
+
|
120 |
+
ans_id = shortuuid.uuid()
|
121 |
+
ans_file.write(json.dumps({"question_id": idx,
|
122 |
+
"prompt": cur_prompt,
|
123 |
+
"text": outputs,
|
124 |
+
"answer_id": ans_id,
|
125 |
+
"model_id": model_name,
|
126 |
+
"metadata": {}}) + "\n")
|
127 |
+
ans_file.flush()
|
128 |
+
ans_file.close()
|
129 |
+
|
130 |
+
if __name__ == "__main__":
|
131 |
+
parser = argparse.ArgumentParser()
|
132 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
133 |
+
parser.add_argument("--model-base", type=str, default=None)
|
134 |
+
parser.add_argument("--image-folder", type=str, default="")
|
135 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
136 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
137 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
138 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
139 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
140 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
141 |
+
parser.add_argument("--top_p", type=float, default=None)
|
142 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
143 |
+
args = parser.parse_args()
|
144 |
+
|
145 |
+
eval_model(args)
|
llava/eval/model_qa.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria
|
3 |
+
import torch
|
4 |
+
import os
|
5 |
+
import json
|
6 |
+
from tqdm import tqdm
|
7 |
+
import shortuuid
|
8 |
+
|
9 |
+
from llava.conversation import default_conversation
|
10 |
+
from llava.utils import disable_torch_init
|
11 |
+
|
12 |
+
|
13 |
+
# new stopping implementation
|
14 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
15 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
16 |
+
self.keywords = keywords
|
17 |
+
self.tokenizer = tokenizer
|
18 |
+
self.start_len = None
|
19 |
+
self.input_ids = input_ids
|
20 |
+
|
21 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
22 |
+
if self.start_len is None:
|
23 |
+
self.start_len = self.input_ids.shape[1]
|
24 |
+
else:
|
25 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, self.start_len:], skip_special_tokens=True)[0]
|
26 |
+
for keyword in self.keywords:
|
27 |
+
if keyword in outputs:
|
28 |
+
return True
|
29 |
+
return False
|
30 |
+
|
31 |
+
|
32 |
+
@torch.inference_mode()
|
33 |
+
def eval_model(model_name, questions_file, answers_file):
|
34 |
+
# Model
|
35 |
+
disable_torch_init()
|
36 |
+
model_name = os.path.expanduser(model_name)
|
37 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
|
38 |
+
model = AutoModelForCausalLM.from_pretrained(model_name,
|
39 |
+
torch_dtype=torch.float16).cuda()
|
40 |
+
|
41 |
+
|
42 |
+
ques_file = open(os.path.expanduser(questions_file), "r")
|
43 |
+
ans_file = open(os.path.expanduser(answers_file), "w")
|
44 |
+
for i, line in enumerate(tqdm(ques_file)):
|
45 |
+
idx = json.loads(line)["question_id"]
|
46 |
+
qs = json.loads(line)["text"]
|
47 |
+
cat = json.loads(line)["category"]
|
48 |
+
conv = default_conversation.copy()
|
49 |
+
conv.append_message(conv.roles[0], qs)
|
50 |
+
prompt = conv.get_prompt()
|
51 |
+
inputs = tokenizer([prompt])
|
52 |
+
input_ids = torch.as_tensor(inputs.input_ids).cuda()
|
53 |
+
stopping_criteria = KeywordsStoppingCriteria([conv.sep], tokenizer, input_ids)
|
54 |
+
output_ids = model.generate(
|
55 |
+
input_ids,
|
56 |
+
do_sample=True,
|
57 |
+
use_cache=True,
|
58 |
+
temperature=0.7,
|
59 |
+
max_new_tokens=1024,
|
60 |
+
stopping_criteria=[stopping_criteria])
|
61 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
|
62 |
+
try:
|
63 |
+
index = outputs.index(conv.sep, len(prompt))
|
64 |
+
except ValueError:
|
65 |
+
outputs += conv.sep
|
66 |
+
index = outputs.index(conv.sep, len(prompt))
|
67 |
+
|
68 |
+
outputs = outputs[len(prompt) + len(conv.roles[1]) + 2:index].strip()
|
69 |
+
ans_id = shortuuid.uuid()
|
70 |
+
ans_file.write(json.dumps({"question_id": idx,
|
71 |
+
"text": outputs,
|
72 |
+
"answer_id": ans_id,
|
73 |
+
"model_id": model_name,
|
74 |
+
"metadata": {}}) + "\n")
|
75 |
+
ans_file.flush()
|
76 |
+
ans_file.close()
|
77 |
+
|
78 |
+
if __name__ == "__main__":
|
79 |
+
parser = argparse.ArgumentParser()
|
80 |
+
parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
|
81 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
82 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
83 |
+
args = parser.parse_args()
|
84 |
+
|
85 |
+
eval_model(args.model_name, args.question_file, args.answers_file)
|
llava/eval/model_vqa.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava.model.builder import load_pretrained_model
|
11 |
+
from llava.utils import disable_torch_init
|
12 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
13 |
+
|
14 |
+
from PIL import Image
|
15 |
+
import math
|
16 |
+
|
17 |
+
|
18 |
+
def split_list(lst, n):
|
19 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
20 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
21 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
22 |
+
|
23 |
+
|
24 |
+
def get_chunk(lst, n, k):
|
25 |
+
chunks = split_list(lst, n)
|
26 |
+
return chunks[k]
|
27 |
+
|
28 |
+
|
29 |
+
def eval_model(args):
|
30 |
+
# Model
|
31 |
+
disable_torch_init()
|
32 |
+
model_path = os.path.expanduser(args.model_path)
|
33 |
+
model_name = get_model_name_from_path(model_path)
|
34 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
35 |
+
|
36 |
+
questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
37 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
38 |
+
answers_file = os.path.expanduser(args.answers_file)
|
39 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
40 |
+
ans_file = open(answers_file, "w")
|
41 |
+
for line in tqdm(questions):
|
42 |
+
idx = line["question_id"]
|
43 |
+
image_file = line["image"]
|
44 |
+
qs = line["text"]
|
45 |
+
cur_prompt = qs
|
46 |
+
if model.config.mm_use_im_start_end:
|
47 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
48 |
+
else:
|
49 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
50 |
+
|
51 |
+
conv = conv_templates[args.conv_mode].copy()
|
52 |
+
conv.append_message(conv.roles[0], qs)
|
53 |
+
conv.append_message(conv.roles[1], None)
|
54 |
+
prompt = conv.get_prompt()
|
55 |
+
|
56 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
57 |
+
|
58 |
+
image = Image.open(os.path.join(args.image_folder, image_file))
|
59 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
60 |
+
|
61 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
62 |
+
keywords = [stop_str]
|
63 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
64 |
+
|
65 |
+
with torch.inference_mode():
|
66 |
+
output_ids = model.generate(
|
67 |
+
input_ids,
|
68 |
+
images=image_tensor.unsqueeze(0).half().cuda(),
|
69 |
+
do_sample=True,
|
70 |
+
temperature=args.temperature,
|
71 |
+
top_p=args.top_p,
|
72 |
+
num_beams=args.num_beams,
|
73 |
+
# no_repeat_ngram_size=3,
|
74 |
+
max_new_tokens=1024,
|
75 |
+
use_cache=True)
|
76 |
+
|
77 |
+
input_token_len = input_ids.shape[1]
|
78 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
79 |
+
if n_diff_input_output > 0:
|
80 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
81 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
82 |
+
outputs = outputs.strip()
|
83 |
+
if outputs.endswith(stop_str):
|
84 |
+
outputs = outputs[:-len(stop_str)]
|
85 |
+
outputs = outputs.strip()
|
86 |
+
|
87 |
+
ans_id = shortuuid.uuid()
|
88 |
+
ans_file.write(json.dumps({"question_id": idx,
|
89 |
+
"prompt": cur_prompt,
|
90 |
+
"text": outputs,
|
91 |
+
"answer_id": ans_id,
|
92 |
+
"model_id": model_name,
|
93 |
+
"metadata": {}}) + "\n")
|
94 |
+
ans_file.flush()
|
95 |
+
ans_file.close()
|
96 |
+
|
97 |
+
if __name__ == "__main__":
|
98 |
+
parser = argparse.ArgumentParser()
|
99 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
100 |
+
parser.add_argument("--model-base", type=str, default=None)
|
101 |
+
parser.add_argument("--image-folder", type=str, default="")
|
102 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
103 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
104 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
105 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
106 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
107 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
108 |
+
parser.add_argument("--top_p", type=float, default=None)
|
109 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
110 |
+
args = parser.parse_args()
|
111 |
+
|
112 |
+
eval_model(args)
|
llava/eval/model_vqa_loader.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava.model.builder import load_pretrained_model
|
11 |
+
from llava.utils import disable_torch_init
|
12 |
+
from llava.mm_utils import tokenizer_image_token, process_images, get_model_name_from_path
|
13 |
+
from torch.utils.data import Dataset, DataLoader
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import math
|
17 |
+
|
18 |
+
|
19 |
+
def split_list(lst, n):
|
20 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
21 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
22 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
23 |
+
|
24 |
+
|
25 |
+
def get_chunk(lst, n, k):
|
26 |
+
chunks = split_list(lst, n)
|
27 |
+
return chunks[k]
|
28 |
+
|
29 |
+
|
30 |
+
# Custom dataset class
|
31 |
+
class CustomDataset(Dataset):
|
32 |
+
def __init__(self, questions, image_folder, tokenizer, image_processor, model_config):
|
33 |
+
self.questions = questions
|
34 |
+
self.image_folder = image_folder
|
35 |
+
self.tokenizer = tokenizer
|
36 |
+
self.image_processor = image_processor
|
37 |
+
self.model_config = model_config
|
38 |
+
|
39 |
+
def __getitem__(self, index):
|
40 |
+
line = self.questions[index]
|
41 |
+
image_file = line["image"]
|
42 |
+
qs = line["text"]
|
43 |
+
if self.model_config.mm_use_im_start_end:
|
44 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
45 |
+
else:
|
46 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
47 |
+
|
48 |
+
conv = conv_templates[args.conv_mode].copy()
|
49 |
+
conv.append_message(conv.roles[0], qs)
|
50 |
+
conv.append_message(conv.roles[1], None)
|
51 |
+
prompt = conv.get_prompt()
|
52 |
+
|
53 |
+
image = Image.open(os.path.join(self.image_folder, image_file)).convert('RGB')
|
54 |
+
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
|
55 |
+
|
56 |
+
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
|
57 |
+
|
58 |
+
return input_ids, image_tensor
|
59 |
+
|
60 |
+
def __len__(self):
|
61 |
+
return len(self.questions)
|
62 |
+
|
63 |
+
|
64 |
+
# DataLoader
|
65 |
+
def create_data_loader(questions, image_folder, tokenizer, image_processor, model_config, batch_size=1, num_workers=4):
|
66 |
+
assert batch_size == 1, "batch_size must be 1"
|
67 |
+
dataset = CustomDataset(questions, image_folder, tokenizer, image_processor, model_config)
|
68 |
+
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
|
69 |
+
return data_loader
|
70 |
+
|
71 |
+
|
72 |
+
def eval_model(args):
|
73 |
+
# Model
|
74 |
+
disable_torch_init()
|
75 |
+
model_path = os.path.expanduser(args.model_path)
|
76 |
+
model_name = get_model_name_from_path(model_path)
|
77 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
78 |
+
|
79 |
+
questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
80 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
81 |
+
answers_file = os.path.expanduser(args.answers_file)
|
82 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
83 |
+
ans_file = open(answers_file, "w")
|
84 |
+
|
85 |
+
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
86 |
+
args.conv_mode = args.conv_mode + '_mmtag'
|
87 |
+
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
88 |
+
|
89 |
+
data_loader = create_data_loader(questions, args.image_folder, tokenizer, image_processor, model.config)
|
90 |
+
|
91 |
+
for (input_ids, image_tensor), line in tqdm(zip(data_loader, questions), total=len(questions)):
|
92 |
+
idx = line["question_id"]
|
93 |
+
cur_prompt = line["text"]
|
94 |
+
|
95 |
+
stop_str = conv_templates[args.conv_mode].sep if conv_templates[args.conv_mode].sep_style != SeparatorStyle.TWO else conv_templates[args.conv_mode].sep2
|
96 |
+
input_ids = input_ids.to(device='cuda', non_blocking=True)
|
97 |
+
|
98 |
+
with torch.inference_mode():
|
99 |
+
output_ids = model.generate(
|
100 |
+
input_ids,
|
101 |
+
images=image_tensor.to(dtype=torch.float16, device='cuda', non_blocking=True),
|
102 |
+
do_sample=True if args.temperature > 0 else False,
|
103 |
+
temperature=args.temperature,
|
104 |
+
top_p=args.top_p,
|
105 |
+
num_beams=args.num_beams,
|
106 |
+
max_new_tokens=128,
|
107 |
+
# max_length=64,
|
108 |
+
use_cache=True)
|
109 |
+
|
110 |
+
input_token_len = input_ids.shape[1]
|
111 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
112 |
+
if n_diff_input_output > 0:
|
113 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
114 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
115 |
+
outputs = outputs.strip()
|
116 |
+
if outputs.endswith(stop_str):
|
117 |
+
outputs = outputs[:-len(stop_str)]
|
118 |
+
outputs = outputs.strip()
|
119 |
+
|
120 |
+
ans_id = shortuuid.uuid()
|
121 |
+
ans_file.write(json.dumps({"question_id": idx,
|
122 |
+
"prompt": cur_prompt,
|
123 |
+
"text": outputs,
|
124 |
+
"answer_id": ans_id,
|
125 |
+
"model_id": model_name,
|
126 |
+
"metadata": {}}) + "\n")
|
127 |
+
ans_file.flush()
|
128 |
+
ans_file.close()
|
129 |
+
|
130 |
+
if __name__ == "__main__":
|
131 |
+
parser = argparse.ArgumentParser()
|
132 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
133 |
+
parser.add_argument("--model-base", type=str, default=None)
|
134 |
+
parser.add_argument("--image-folder", type=str, default="")
|
135 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
136 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
137 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
138 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
139 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
140 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
141 |
+
parser.add_argument("--top_p", type=float, default=None)
|
142 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
143 |
+
args = parser.parse_args()
|
144 |
+
|
145 |
+
eval_model(args)
|
llava/eval/model_vqa_mmbench.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import pandas as pd
|
6 |
+
from tqdm import tqdm
|
7 |
+
import shortuuid
|
8 |
+
|
9 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
10 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
11 |
+
from llava.model.builder import load_pretrained_model
|
12 |
+
from llava.utils import disable_torch_init
|
13 |
+
from llava.mm_utils import tokenizer_image_token, process_images, load_image_from_base64, get_model_name_from_path
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import math
|
17 |
+
|
18 |
+
|
19 |
+
all_options = ['A', 'B', 'C', 'D']
|
20 |
+
|
21 |
+
|
22 |
+
def split_list(lst, n):
|
23 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
24 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
25 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
26 |
+
|
27 |
+
|
28 |
+
def get_chunk(lst, n, k):
|
29 |
+
chunks = split_list(lst, n)
|
30 |
+
return chunks[k]
|
31 |
+
|
32 |
+
|
33 |
+
def is_none(value):
|
34 |
+
if value is None:
|
35 |
+
return True
|
36 |
+
if type(value) is float and math.isnan(value):
|
37 |
+
return True
|
38 |
+
if type(value) is str and value.lower() == 'nan':
|
39 |
+
return True
|
40 |
+
if type(value) is str and value.lower() == 'none':
|
41 |
+
return True
|
42 |
+
return False
|
43 |
+
|
44 |
+
def get_options(row, options):
|
45 |
+
parsed_options = []
|
46 |
+
for option in options:
|
47 |
+
option_value = row[option]
|
48 |
+
if is_none(option_value):
|
49 |
+
break
|
50 |
+
parsed_options.append(option_value)
|
51 |
+
return parsed_options
|
52 |
+
|
53 |
+
|
54 |
+
def eval_model(args):
|
55 |
+
# Model
|
56 |
+
disable_torch_init()
|
57 |
+
model_path = os.path.expanduser(args.model_path)
|
58 |
+
model_name = get_model_name_from_path(model_path)
|
59 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
60 |
+
|
61 |
+
questions = pd.read_table(os.path.expanduser(args.question_file))
|
62 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
63 |
+
answers_file = os.path.expanduser(args.answers_file)
|
64 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
65 |
+
ans_file = open(answers_file, "w")
|
66 |
+
|
67 |
+
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
|
68 |
+
args.conv_mode = args.conv_mode + '_mmtag'
|
69 |
+
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
|
70 |
+
|
71 |
+
for index, row in tqdm(questions.iterrows(), total=len(questions)):
|
72 |
+
options = get_options(row, all_options)
|
73 |
+
cur_option_char = all_options[:len(options)]
|
74 |
+
|
75 |
+
if args.all_rounds:
|
76 |
+
num_rounds = len(options)
|
77 |
+
else:
|
78 |
+
num_rounds = 1
|
79 |
+
|
80 |
+
for round_idx in range(num_rounds):
|
81 |
+
idx = row['index']
|
82 |
+
question = row['question']
|
83 |
+
hint = row['hint']
|
84 |
+
image = load_image_from_base64(row['image'])
|
85 |
+
if not is_none(hint):
|
86 |
+
question = hint + '\n' + question
|
87 |
+
for option_char, option in zip(all_options[:len(options)], options):
|
88 |
+
question = question + '\n' + option_char + '. ' + option
|
89 |
+
qs = cur_prompt = question
|
90 |
+
if model.config.mm_use_im_start_end:
|
91 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
92 |
+
else:
|
93 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
94 |
+
|
95 |
+
if args.single_pred_prompt:
|
96 |
+
if args.lang == 'cn':
|
97 |
+
qs = qs + '\n' + "请直接回答选项字母。"
|
98 |
+
else:
|
99 |
+
qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
|
100 |
+
|
101 |
+
conv = conv_templates[args.conv_mode].copy()
|
102 |
+
conv.append_message(conv.roles[0], qs)
|
103 |
+
conv.append_message(conv.roles[1], None)
|
104 |
+
prompt = conv.get_prompt()
|
105 |
+
|
106 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
107 |
+
|
108 |
+
image_tensor = process_images([image], image_processor, model.config)[0]
|
109 |
+
# image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
110 |
+
|
111 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
112 |
+
|
113 |
+
with torch.inference_mode():
|
114 |
+
output_ids = model.generate(
|
115 |
+
input_ids,
|
116 |
+
images=image_tensor.unsqueeze(0).half().cuda(),
|
117 |
+
do_sample=True if args.temperature > 0 else False,
|
118 |
+
temperature=args.temperature,
|
119 |
+
top_p=args.top_p,
|
120 |
+
num_beams=args.num_beams,
|
121 |
+
# no_repeat_ngram_size=3,
|
122 |
+
max_new_tokens=1024,
|
123 |
+
use_cache=True)
|
124 |
+
|
125 |
+
input_token_len = input_ids.shape[1]
|
126 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
127 |
+
if n_diff_input_output > 0:
|
128 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
129 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
130 |
+
outputs = outputs.strip()
|
131 |
+
if outputs.endswith(stop_str):
|
132 |
+
outputs = outputs[:-len(stop_str)]
|
133 |
+
outputs = outputs.strip()
|
134 |
+
|
135 |
+
ans_id = shortuuid.uuid()
|
136 |
+
ans_file.write(json.dumps({"question_id": idx,
|
137 |
+
"round_id": round_idx,
|
138 |
+
"prompt": cur_prompt,
|
139 |
+
"text": outputs,
|
140 |
+
"options": options,
|
141 |
+
"option_char": cur_option_char,
|
142 |
+
"answer_id": ans_id,
|
143 |
+
"model_id": model_name,
|
144 |
+
"metadata": {}}) + "\n")
|
145 |
+
ans_file.flush()
|
146 |
+
|
147 |
+
# rotate options
|
148 |
+
options = options[1:] + options[:1]
|
149 |
+
cur_option_char = cur_option_char[1:] + cur_option_char[:1]
|
150 |
+
ans_file.close()
|
151 |
+
|
152 |
+
if __name__ == "__main__":
|
153 |
+
parser = argparse.ArgumentParser()
|
154 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
155 |
+
parser.add_argument("--model-base", type=str, default=None)
|
156 |
+
parser.add_argument("--image-folder", type=str, default="")
|
157 |
+
parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
|
158 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
159 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
160 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
161 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
162 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
163 |
+
parser.add_argument("--top_p", type=float, default=None)
|
164 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
165 |
+
parser.add_argument("--all-rounds", action="store_true")
|
166 |
+
parser.add_argument("--single-pred-prompt", action="store_true")
|
167 |
+
parser.add_argument("--lang", type=str, default="en")
|
168 |
+
args = parser.parse_args()
|
169 |
+
|
170 |
+
eval_model(args)
|
llava/eval/model_vqa_qbench.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
from tqdm import tqdm
|
4 |
+
import json
|
5 |
+
|
6 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
7 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
8 |
+
from llava.model.builder import load_pretrained_model
|
9 |
+
from llava.utils import disable_torch_init
|
10 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
11 |
+
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
import requests
|
15 |
+
from PIL import Image
|
16 |
+
from io import BytesIO
|
17 |
+
|
18 |
+
|
19 |
+
def load_image(image_file):
|
20 |
+
if image_file.startswith('http') or image_file.startswith('https'):
|
21 |
+
response = requests.get(image_file)
|
22 |
+
image = Image.open(BytesIO(response.content)).convert('RGB')
|
23 |
+
else:
|
24 |
+
image = Image.open(image_file).convert('RGB')
|
25 |
+
return image
|
26 |
+
|
27 |
+
|
28 |
+
def eval_model(args):
|
29 |
+
# Model
|
30 |
+
disable_torch_init()
|
31 |
+
|
32 |
+
model_name = get_model_name_from_path(args.model_path)
|
33 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, True)
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
with open(args.questions_file) as f:
|
39 |
+
llvqa_data = json.load(f)
|
40 |
+
|
41 |
+
for i, llddata in enumerate(tqdm(llvqa_data)):
|
42 |
+
filename = llddata["img_path"]
|
43 |
+
if args.lang == "en":
|
44 |
+
message = llddata["question"] + "\nChoose between one of the options as follows:\n"
|
45 |
+
elif args.lang == "zh":
|
46 |
+
message = llddata["question"] + "\在下列选项中选择一个:\n"
|
47 |
+
else:
|
48 |
+
raise NotImplementedError("Q-Bench does not support languages other than English (en) and Chinese (zh) yet. Contact us (https://github.com/VQAssessment/Q-Bench/) to convert Q-Bench into more languages.")
|
49 |
+
for choice, ans in zip(["A.", "B.", "C.", "D."], llddata["candidates"]):
|
50 |
+
message += f"{choice} {ans}\n"
|
51 |
+
qs = message
|
52 |
+
|
53 |
+
if model.config.mm_use_im_start_end:
|
54 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
55 |
+
else:
|
56 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
57 |
+
|
58 |
+
if 'llama-2' in model_name.lower():
|
59 |
+
conv_mode = "llava_llama_2"
|
60 |
+
elif "v1" in model_name.lower():
|
61 |
+
conv_mode = "llava_v1"
|
62 |
+
elif "mpt" in model_name.lower():
|
63 |
+
conv_mode = "mpt"
|
64 |
+
else:
|
65 |
+
conv_mode = "llava_v0"
|
66 |
+
|
67 |
+
if args.conv_mode is not None and conv_mode != args.conv_mode:
|
68 |
+
print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
|
69 |
+
else:
|
70 |
+
args.conv_mode = conv_mode
|
71 |
+
|
72 |
+
conv = conv_templates[args.conv_mode].copy()
|
73 |
+
conv.append_message(conv.roles[0], qs)
|
74 |
+
conv.append_message(conv.roles[1], None)
|
75 |
+
prompt = conv.get_prompt()
|
76 |
+
|
77 |
+
image = load_image(args.image_folder + filename)
|
78 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda()
|
79 |
+
|
80 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
81 |
+
|
82 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
83 |
+
keywords = [stop_str]
|
84 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
85 |
+
|
86 |
+
|
87 |
+
with torch.inference_mode():
|
88 |
+
output_ids = model.generate(
|
89 |
+
input_ids,
|
90 |
+
images=image_tensor,
|
91 |
+
num_beams=1,
|
92 |
+
do_sample=False,
|
93 |
+
temperature=0,
|
94 |
+
max_new_tokens=1024,
|
95 |
+
use_cache=True,
|
96 |
+
stopping_criteria=[stopping_criteria])
|
97 |
+
|
98 |
+
input_token_len = input_ids.shape[1]
|
99 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
100 |
+
if n_diff_input_output > 0:
|
101 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
102 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
103 |
+
outputs = outputs.strip()
|
104 |
+
if outputs.endswith(stop_str):
|
105 |
+
outputs = outputs[:-len(stop_str)]
|
106 |
+
outputs = outputs.strip()
|
107 |
+
llddata["response"] = outputs
|
108 |
+
with open(args.answers_file, "a") as wf:
|
109 |
+
json.dump(llddata, wf)
|
110 |
+
|
111 |
+
if __name__ == "__main__":
|
112 |
+
parser = argparse.ArgumentParser()
|
113 |
+
parser.add_argument("--model-path", type=str, default="llava-v1.5")
|
114 |
+
parser.add_argument("--model-base", type=str, default=None)
|
115 |
+
parser.add_argument("--image-folder", type=str, default="./playground/data/qbench/images_llvisionqa")
|
116 |
+
parser.add_argument("--questions-file", type=str, default="./playground/data/qbench/llvisionqa_dev.json")
|
117 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
118 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
119 |
+
parser.add_argument("--lang", type=str, default="en")
|
120 |
+
args = parser.parse_args()
|
121 |
+
|
122 |
+
eval_model(args)
|
llava/eval/model_vqa_science.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from tqdm import tqdm
|
6 |
+
import shortuuid
|
7 |
+
|
8 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
9 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
10 |
+
from llava.model.builder import load_pretrained_model
|
11 |
+
from llava.utils import disable_torch_init
|
12 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
13 |
+
|
14 |
+
from PIL import Image
|
15 |
+
import math
|
16 |
+
|
17 |
+
|
18 |
+
def split_list(lst, n):
|
19 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
20 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
21 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
22 |
+
|
23 |
+
|
24 |
+
def get_chunk(lst, n, k):
|
25 |
+
chunks = split_list(lst, n)
|
26 |
+
return chunks[k]
|
27 |
+
|
28 |
+
|
29 |
+
def eval_model(args):
|
30 |
+
# Model
|
31 |
+
disable_torch_init()
|
32 |
+
model_path = os.path.expanduser(args.model_path)
|
33 |
+
model_name = get_model_name_from_path(model_path)
|
34 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name)
|
35 |
+
|
36 |
+
questions = json.load(open(os.path.expanduser(args.question_file), "r"))
|
37 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
38 |
+
answers_file = os.path.expanduser(args.answers_file)
|
39 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
40 |
+
ans_file = open(answers_file, "w")
|
41 |
+
for i, line in enumerate(tqdm(questions)):
|
42 |
+
idx = line["id"]
|
43 |
+
question = line['conversations'][0]
|
44 |
+
qs = question['value'].replace('<image>', '').strip()
|
45 |
+
cur_prompt = qs
|
46 |
+
|
47 |
+
if 'image' in line:
|
48 |
+
image_file = line["image"]
|
49 |
+
image = Image.open(os.path.join(args.image_folder, image_file))
|
50 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
51 |
+
images = image_tensor.unsqueeze(0).half().cuda()
|
52 |
+
if getattr(model.config, 'mm_use_im_start_end', False):
|
53 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
54 |
+
else:
|
55 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
56 |
+
cur_prompt = '<image>' + '\n' + cur_prompt
|
57 |
+
else:
|
58 |
+
images = None
|
59 |
+
|
60 |
+
conv = conv_templates[args.conv_mode].copy()
|
61 |
+
conv.append_message(conv.roles[0], qs)
|
62 |
+
conv.append_message(conv.roles[1], None)
|
63 |
+
prompt = conv.get_prompt()
|
64 |
+
|
65 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
66 |
+
|
67 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
68 |
+
keywords = [stop_str]
|
69 |
+
stopping_criteria = [KeywordsStoppingCriteria(keywords, tokenizer, input_ids)] if conv.version == "v0" else None
|
70 |
+
|
71 |
+
with torch.inference_mode():
|
72 |
+
output_ids = model.generate(
|
73 |
+
input_ids,
|
74 |
+
images=images,
|
75 |
+
do_sample=True,
|
76 |
+
temperature=0.2,
|
77 |
+
max_new_tokens=1024,
|
78 |
+
use_cache=True,
|
79 |
+
stopping_criteria=stopping_criteria,
|
80 |
+
)
|
81 |
+
|
82 |
+
input_token_len = input_ids.shape[1]
|
83 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
84 |
+
if n_diff_input_output > 0:
|
85 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
86 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
87 |
+
outputs = outputs.strip()
|
88 |
+
if outputs.endswith(stop_str):
|
89 |
+
outputs = outputs[:-len(stop_str)]
|
90 |
+
outputs = outputs.strip()
|
91 |
+
|
92 |
+
# prompt for answer
|
93 |
+
if args.answer_prompter:
|
94 |
+
outputs_reasoning = outputs
|
95 |
+
input_ids = tokenizer_image_token(prompt + outputs_reasoning + ' ###\nANSWER:', tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
96 |
+
|
97 |
+
with torch.inference_mode():
|
98 |
+
output_ids = model.generate(
|
99 |
+
input_ids,
|
100 |
+
images=images,
|
101 |
+
do_sample=True,
|
102 |
+
temperature=0.2,
|
103 |
+
max_new_tokens=64,
|
104 |
+
use_cache=True,
|
105 |
+
stopping_criteria=[stopping_criteria])
|
106 |
+
|
107 |
+
input_token_len = input_ids.shape[1]
|
108 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
109 |
+
if n_diff_input_output > 0:
|
110 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
111 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
112 |
+
outputs = outputs.strip()
|
113 |
+
if outputs.endswith(stop_str):
|
114 |
+
outputs = outputs[:-len(stop_str)]
|
115 |
+
outputs = outputs.strip()
|
116 |
+
outputs = outputs_reasoning + '\n The answer is ' + outputs
|
117 |
+
|
118 |
+
ans_id = shortuuid.uuid()
|
119 |
+
ans_file.write(json.dumps({"question_id": idx,
|
120 |
+
"prompt": cur_prompt,
|
121 |
+
"text": outputs,
|
122 |
+
"answer_id": ans_id,
|
123 |
+
"model_id": model_name,
|
124 |
+
"metadata": {}}) + "\n")
|
125 |
+
ans_file.flush()
|
126 |
+
ans_file.close()
|
127 |
+
|
128 |
+
if __name__ == "__main__":
|
129 |
+
parser = argparse.ArgumentParser()
|
130 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
131 |
+
parser.add_argument("--model-base", type=str, default=None)
|
132 |
+
parser.add_argument("--image-folder", type=str, default="")
|
133 |
+
parser.add_argument("--question-file", type=str, default="tables/question.json")
|
134 |
+
parser.add_argument("--answers-file", type=str, default="answer.jsonl")
|
135 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v0")
|
136 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
137 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
138 |
+
parser.add_argument("--answer-prompter", action="store_true")
|
139 |
+
args = parser.parse_args()
|
140 |
+
|
141 |
+
eval_model(args)
|
llava/eval/qa_baseline_gpt35.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Generate answers with GPT-3.5"""
|
2 |
+
# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
|
3 |
+
import argparse
|
4 |
+
import json
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
import concurrent.futures
|
8 |
+
|
9 |
+
import openai
|
10 |
+
import tqdm
|
11 |
+
import shortuuid
|
12 |
+
|
13 |
+
MODEL = 'gpt-3.5-turbo'
|
14 |
+
MODEL_ID = 'gpt-3.5-turbo:20230327'
|
15 |
+
|
16 |
+
def get_answer(question_id: int, question: str, max_tokens: int):
|
17 |
+
ans = {
|
18 |
+
'answer_id': shortuuid.uuid(),
|
19 |
+
'question_id': question_id,
|
20 |
+
'model_id': MODEL_ID,
|
21 |
+
}
|
22 |
+
for _ in range(3):
|
23 |
+
try:
|
24 |
+
response = openai.ChatCompletion.create(
|
25 |
+
model=MODEL,
|
26 |
+
messages=[{
|
27 |
+
'role': 'system',
|
28 |
+
'content': 'You are a helpful assistant.'
|
29 |
+
}, {
|
30 |
+
'role': 'user',
|
31 |
+
'content': question,
|
32 |
+
}],
|
33 |
+
max_tokens=max_tokens,
|
34 |
+
)
|
35 |
+
ans['text'] = response['choices'][0]['message']['content']
|
36 |
+
return ans
|
37 |
+
except Exception as e:
|
38 |
+
print('[ERROR]', e)
|
39 |
+
ans['text'] = '#ERROR#'
|
40 |
+
time.sleep(1)
|
41 |
+
return ans
|
42 |
+
|
43 |
+
|
44 |
+
if __name__ == '__main__':
|
45 |
+
parser = argparse.ArgumentParser(description='ChatGPT answer generation.')
|
46 |
+
parser.add_argument('-q', '--question')
|
47 |
+
parser.add_argument('-o', '--output')
|
48 |
+
parser.add_argument('--max-tokens', type=int, default=1024, help='maximum number of tokens produced in the output')
|
49 |
+
args = parser.parse_args()
|
50 |
+
|
51 |
+
questions_dict = {}
|
52 |
+
with open(os.path.expanduser(args.question)) as f:
|
53 |
+
for line in f:
|
54 |
+
if not line:
|
55 |
+
continue
|
56 |
+
q = json.loads(line)
|
57 |
+
questions_dict[q['question_id']] = q['text']
|
58 |
+
|
59 |
+
answers = []
|
60 |
+
|
61 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
|
62 |
+
futures = []
|
63 |
+
for qid, question in questions_dict.items():
|
64 |
+
future = executor.submit(get_answer, qid, question, args.max_tokens)
|
65 |
+
futures.append(future)
|
66 |
+
|
67 |
+
for future in tqdm.tqdm(concurrent.futures.as_completed(futures), total=len(futures)):
|
68 |
+
answers.append(future.result())
|
69 |
+
|
70 |
+
answers.sort(key=lambda x: x['question_id'])
|
71 |
+
|
72 |
+
with open(os.path.expanduser(args.output), 'w') as f:
|
73 |
+
table = [json.dumps(ans) for ans in answers]
|
74 |
+
f.write('\n'.join(table))
|
llava/eval/run_llava.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
5 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
6 |
+
from llava.model.builder import load_pretrained_model
|
7 |
+
from llava.utils import disable_torch_init
|
8 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
|
9 |
+
|
10 |
+
from PIL import Image
|
11 |
+
|
12 |
+
import requests
|
13 |
+
from PIL import Image
|
14 |
+
from io import BytesIO
|
15 |
+
|
16 |
+
|
17 |
+
def load_image(image_file):
|
18 |
+
if image_file.startswith('http') or image_file.startswith('https'):
|
19 |
+
response = requests.get(image_file)
|
20 |
+
image = Image.open(BytesIO(response.content)).convert('RGB')
|
21 |
+
else:
|
22 |
+
image = Image.open(image_file).convert('RGB')
|
23 |
+
return image
|
24 |
+
|
25 |
+
|
26 |
+
def eval_model(args):
|
27 |
+
# Model
|
28 |
+
disable_torch_init()
|
29 |
+
|
30 |
+
model_name = get_model_name_from_path(args.model_path)
|
31 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
|
32 |
+
|
33 |
+
qs = args.query
|
34 |
+
if model.config.mm_use_im_start_end:
|
35 |
+
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
|
36 |
+
else:
|
37 |
+
qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
|
38 |
+
|
39 |
+
if 'llama-2' in model_name.lower():
|
40 |
+
conv_mode = "llava_llama_2"
|
41 |
+
elif "v1" in model_name.lower():
|
42 |
+
conv_mode = "llava_v1"
|
43 |
+
elif "mpt" in model_name.lower():
|
44 |
+
conv_mode = "mpt"
|
45 |
+
else:
|
46 |
+
conv_mode = "llava_v0"
|
47 |
+
|
48 |
+
if args.conv_mode is not None and conv_mode != args.conv_mode:
|
49 |
+
print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
|
50 |
+
else:
|
51 |
+
args.conv_mode = conv_mode
|
52 |
+
|
53 |
+
conv = conv_templates[args.conv_mode].copy()
|
54 |
+
conv.append_message(conv.roles[0], qs)
|
55 |
+
conv.append_message(conv.roles[1], None)
|
56 |
+
prompt = conv.get_prompt()
|
57 |
+
|
58 |
+
image = load_image(args.image_file)
|
59 |
+
image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].half().cuda()
|
60 |
+
|
61 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
62 |
+
|
63 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
64 |
+
keywords = [stop_str]
|
65 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
66 |
+
|
67 |
+
with torch.inference_mode():
|
68 |
+
output_ids = model.generate(
|
69 |
+
input_ids,
|
70 |
+
images=image_tensor,
|
71 |
+
do_sample=True,
|
72 |
+
temperature=0.2,
|
73 |
+
max_new_tokens=1024,
|
74 |
+
use_cache=True,
|
75 |
+
stopping_criteria=[stopping_criteria])
|
76 |
+
|
77 |
+
input_token_len = input_ids.shape[1]
|
78 |
+
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
|
79 |
+
if n_diff_input_output > 0:
|
80 |
+
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
|
81 |
+
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
|
82 |
+
outputs = outputs.strip()
|
83 |
+
if outputs.endswith(stop_str):
|
84 |
+
outputs = outputs[:-len(stop_str)]
|
85 |
+
outputs = outputs.strip()
|
86 |
+
print(outputs)
|
87 |
+
|
88 |
+
if __name__ == "__main__":
|
89 |
+
parser = argparse.ArgumentParser()
|
90 |
+
parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
|
91 |
+
parser.add_argument("--model-base", type=str, default=None)
|
92 |
+
parser.add_argument("--image-file", type=str, required=True)
|
93 |
+
parser.add_argument("--query", type=str, required=True)
|
94 |
+
parser.add_argument("--conv-mode", type=str, default=None)
|
95 |
+
args = parser.parse_args()
|
96 |
+
|
97 |
+
eval_model(args)
|
llava/eval/summarize_gpt_review.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
from collections import defaultdict
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
import argparse
|
8 |
+
|
9 |
+
def parse_args():
|
10 |
+
parser = argparse.ArgumentParser(description='ChatGPT-based QA evaluation.')
|
11 |
+
parser.add_argument('-d', '--dir', default=None)
|
12 |
+
parser.add_argument('-f', '--files', nargs='*', default=None)
|
13 |
+
parser.add_argument('-i', '--ignore', nargs='*', default=None)
|
14 |
+
return parser.parse_args()
|
15 |
+
|
16 |
+
|
17 |
+
if __name__ == '__main__':
|
18 |
+
args = parse_args()
|
19 |
+
|
20 |
+
if args.ignore is not None:
|
21 |
+
args.ignore = [int(x) for x in args.ignore]
|
22 |
+
|
23 |
+
if args.files is not None and len(args.files) > 0:
|
24 |
+
review_files = args.files
|
25 |
+
else:
|
26 |
+
review_files = [x for x in os.listdir(args.dir) if x.endswith('.jsonl') and (x.startswith('gpt4_text') or x.startswith('reviews_') or x.startswith('review_'))]
|
27 |
+
|
28 |
+
for review_file in sorted(review_files):
|
29 |
+
config = os.path.basename(review_file).replace('gpt4_text_', '').replace('.jsonl', '')
|
30 |
+
scores = defaultdict(list)
|
31 |
+
print(config)
|
32 |
+
with open(os.path.join(args.dir, review_file) if args.dir is not None else review_file) as f:
|
33 |
+
for review_str in f:
|
34 |
+
review = json.loads(review_str)
|
35 |
+
if args.ignore is not None and review['question_id'] in args.ignore:
|
36 |
+
continue
|
37 |
+
if 'category' in review:
|
38 |
+
scores[review['category']].append(review['tuple'])
|
39 |
+
scores['all'].append(review['tuple'])
|
40 |
+
else:
|
41 |
+
if 'tuple' in review:
|
42 |
+
scores['all'].append(review['tuple'])
|
43 |
+
else:
|
44 |
+
scores['all'].append(review['score'])
|
45 |
+
for k, v in sorted(scores.items()):
|
46 |
+
stats = np.asarray(v).mean(0).tolist()
|
47 |
+
stats = [round(x, 3) for x in stats]
|
48 |
+
# print(k, stats, round(stats[1]/stats[0]*100, 1))
|
49 |
+
print(k, round(stats[1]/stats[0]*100, 1))
|
50 |
+
print('=================================')
|
llava/eval/webpage/figures/alpaca.png
ADDED
llava/eval/webpage/figures/bard.jpg
ADDED
llava/eval/webpage/figures/chatgpt.svg
ADDED
llava/eval/webpage/figures/llama.jpg
ADDED
llava/eval/webpage/figures/swords_FILL0_wght300_GRAD0_opsz48.svg
ADDED