Add files using upload-large-folder tool
Browse files- spatial-model/VLM-3R/llava/__init__.py +1 -0
- spatial-model/VLM-3R/llava/conversation.py +585 -0
- spatial-model/VLM-3R/llava/eval/eval_sqa3d.py +93 -0
- spatial-model/VLM-3R/llava/eval/evaluate_interleave.py +339 -0
- spatial-model/VLM-3R/llava/eval/model_scanqa.py +133 -0
- spatial-model/VLM-3R/llava/eval/model_sqa3d.py +154 -0
- spatial-model/VLM-3R/llava/eval/model_sqa3d_preload.py +234 -0
- spatial-model/VLM-3R/llava/eval/scanqa_evaluator.py +283 -0
- spatial-model/VLM-3R/llava/mm_utils.py +395 -0
- spatial-model/VLM-3R/llava/model/multimodal_spatial_encoder/builder.py +39 -0
- spatial-model/VLM-3R/llava/model/multimodal_spatial_encoder/cut3r_points.py +342 -0
- spatial-model/VLM-3R/llava/model/multimodal_spatial_encoder/cut3r_spatial_encoder.py +555 -0
- spatial-model/VLM-3R/llava/serve/__init__.py +0 -0
- spatial-model/VLM-3R/llava/serve/controller.py +287 -0
- spatial-model/VLM-3R/llava/serve/gradio_web_server.py +442 -0
- spatial-model/VLM-3R/llava/serve/register_worker.py +26 -0
- spatial-model/VLM-3R/llava/serve/sglang_worker.py +237 -0
- spatial-model/VLM-3R/llava/serve/test_message.py +59 -0
- spatial-model/VLM-3R/llava/spar_utils.py +484 -0
- spatial-model/VLM-3R/thinking-in-space/miscs/llava_result_check.md +0 -0
spatial-model/VLM-3R/llava/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .model import LlavaLlamaForCausalLM
|
spatial-model/VLM-3R/llava/conversation.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from enum import auto, Enum
|
| 3 |
+
from typing import List, Any, Dict, Union, Tuple
|
| 4 |
+
import re
|
| 5 |
+
import base64
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from transformers import AutoTokenizer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SeparatorStyle(Enum):
|
| 12 |
+
"""Different separator style."""
|
| 13 |
+
|
| 14 |
+
SINGLE = auto()
|
| 15 |
+
TWO = auto()
|
| 16 |
+
MPT = auto()
|
| 17 |
+
PLAIN = auto()
|
| 18 |
+
CHATML = auto()
|
| 19 |
+
LLAMA_2 = auto()
|
| 20 |
+
LLAMA_3 = auto()
|
| 21 |
+
QWEN = auto()
|
| 22 |
+
GEMMA = auto()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclasses.dataclass
|
| 26 |
+
class Conversation:
|
| 27 |
+
"""A class that keeps all conversation history."""
|
| 28 |
+
|
| 29 |
+
system: str
|
| 30 |
+
roles: List[str]
|
| 31 |
+
messages: List[List[str]]
|
| 32 |
+
offset: int
|
| 33 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
| 34 |
+
sep: str = "###"
|
| 35 |
+
sep2: str = None
|
| 36 |
+
version: str = "Unknown"
|
| 37 |
+
|
| 38 |
+
tokenizer_id: str = ""
|
| 39 |
+
tokenizer: Any = None
|
| 40 |
+
# Stop criteria (the default one is EOS token)
|
| 41 |
+
stop_str: Union[str, List[str]] = None
|
| 42 |
+
# Stops generation if meeting any token in this list
|
| 43 |
+
stop_token_ids: List[int] = None
|
| 44 |
+
|
| 45 |
+
skip_next: bool = False
|
| 46 |
+
|
| 47 |
+
def get_prompt(self):
|
| 48 |
+
messages = self.messages
|
| 49 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
| 50 |
+
messages = self.messages.copy()
|
| 51 |
+
init_role, init_msg = messages[0].copy()
|
| 52 |
+
init_msg = init_msg[0]
|
| 53 |
+
if "mmtag" in self.version:
|
| 54 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
| 55 |
+
messages[0] = (init_role, init_msg)
|
| 56 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
| 57 |
+
messages.insert(1, (self.roles[1], "Received."))
|
| 58 |
+
elif not init_msg.startswith("<image>"):
|
| 59 |
+
init_msg = init_msg.replace("<image>", "").strip()
|
| 60 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
| 61 |
+
else:
|
| 62 |
+
messages[0] = (init_role, init_msg)
|
| 63 |
+
|
| 64 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
| 65 |
+
ret = self.system + self.sep
|
| 66 |
+
for role, message in messages:
|
| 67 |
+
if message:
|
| 68 |
+
if type(message) is tuple:
|
| 69 |
+
message, _, _ = message
|
| 70 |
+
ret += role + ": " + message + self.sep
|
| 71 |
+
else:
|
| 72 |
+
ret += role + ":"
|
| 73 |
+
|
| 74 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
| 75 |
+
seps = [self.sep, self.sep2]
|
| 76 |
+
ret = self.system + seps[0]
|
| 77 |
+
for i, (role, message) in enumerate(messages):
|
| 78 |
+
if message:
|
| 79 |
+
if type(message) is tuple:
|
| 80 |
+
message, _, _ = message
|
| 81 |
+
ret += role + ": " + message + seps[i % 2]
|
| 82 |
+
else:
|
| 83 |
+
ret += role + ":"
|
| 84 |
+
|
| 85 |
+
elif self.sep_style == SeparatorStyle.CHATML:
|
| 86 |
+
ret = "" if self.system == "" else self.system + self.sep + "\n"
|
| 87 |
+
for role, message in messages:
|
| 88 |
+
if message:
|
| 89 |
+
if type(message) is tuple:
|
| 90 |
+
message, images, _ = message
|
| 91 |
+
message = "<image>" * len(images) + message
|
| 92 |
+
ret += role + "\n" + message + self.sep + "\n"
|
| 93 |
+
else:
|
| 94 |
+
ret += role + "\n"
|
| 95 |
+
return ret
|
| 96 |
+
|
| 97 |
+
elif self.sep_style == SeparatorStyle.LLAMA_3:
|
| 98 |
+
if self.tokenizer is None:
|
| 99 |
+
raise ValueError("Llama 3 tokenizer is not available. Make sure you have the necessary permissions.")
|
| 100 |
+
chat_template_messages = [{"role": "system", "content": self.system}]
|
| 101 |
+
for role, message in messages:
|
| 102 |
+
if message:
|
| 103 |
+
if type(message) is tuple:
|
| 104 |
+
message, images = message
|
| 105 |
+
message = "<image>" * len(images) + message
|
| 106 |
+
chat_template_messages.append({"role": role, "content": message})
|
| 107 |
+
|
| 108 |
+
# print(chat_template_messages)
|
| 109 |
+
return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
|
| 110 |
+
# ret = "" if self.system == "" else self.system + self.sep + "\n"
|
| 111 |
+
# for role, message in messages:
|
| 112 |
+
# if message:
|
| 113 |
+
# if type(message) is tuple:
|
| 114 |
+
# message, images = message
|
| 115 |
+
# message = "<image>" * len(images) + message
|
| 116 |
+
# ret += role + "\n" + message + self.sep + "\n"
|
| 117 |
+
# else:
|
| 118 |
+
# ret += role + "\n"
|
| 119 |
+
# return ret
|
| 120 |
+
|
| 121 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
| 122 |
+
ret = self.system + self.sep
|
| 123 |
+
for role, message in messages:
|
| 124 |
+
if message:
|
| 125 |
+
if type(message) is tuple:
|
| 126 |
+
message, _, _ = message
|
| 127 |
+
ret += role + message + self.sep
|
| 128 |
+
else:
|
| 129 |
+
ret += role
|
| 130 |
+
|
| 131 |
+
elif self.sep_style == SeparatorStyle.GEMMA:
|
| 132 |
+
ret = ""
|
| 133 |
+
for i, (role, message) in enumerate(messages):
|
| 134 |
+
assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
|
| 135 |
+
if message:
|
| 136 |
+
if type(message) is tuple:
|
| 137 |
+
message, _, _ = message
|
| 138 |
+
ret += role + message + self.sep
|
| 139 |
+
else:
|
| 140 |
+
ret += role
|
| 141 |
+
|
| 142 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 143 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
|
| 144 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 145 |
+
ret = ""
|
| 146 |
+
|
| 147 |
+
for i, (role, message) in enumerate(messages):
|
| 148 |
+
if i == 0:
|
| 149 |
+
assert message, "first message should not be none"
|
| 150 |
+
assert role == self.roles[0], "first message should come from user"
|
| 151 |
+
if message:
|
| 152 |
+
if type(message) is tuple:
|
| 153 |
+
message, _, _ = message
|
| 154 |
+
if i == 0:
|
| 155 |
+
message = wrap_sys(self.system) + message
|
| 156 |
+
if i % 2 == 0:
|
| 157 |
+
message = wrap_inst(message)
|
| 158 |
+
ret += self.sep + message
|
| 159 |
+
else:
|
| 160 |
+
ret += " " + message + " " + self.sep2
|
| 161 |
+
else:
|
| 162 |
+
ret += ""
|
| 163 |
+
ret = ret.lstrip(self.sep)
|
| 164 |
+
|
| 165 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
| 166 |
+
seps = [self.sep, self.sep2]
|
| 167 |
+
ret = self.system
|
| 168 |
+
for i, (role, message) in enumerate(messages):
|
| 169 |
+
if message:
|
| 170 |
+
if type(message) is tuple:
|
| 171 |
+
message, _, _ = message
|
| 172 |
+
ret += message + seps[i % 2]
|
| 173 |
+
else:
|
| 174 |
+
ret += ""
|
| 175 |
+
else:
|
| 176 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
| 177 |
+
|
| 178 |
+
return ret
|
| 179 |
+
|
| 180 |
+
def append_message(self, role, message):
|
| 181 |
+
self.messages.append([role, message])
|
| 182 |
+
|
| 183 |
+
def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
|
| 184 |
+
if image_process_mode == "Pad":
|
| 185 |
+
|
| 186 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 187 |
+
width, height = pil_img.size
|
| 188 |
+
if width == height:
|
| 189 |
+
return pil_img
|
| 190 |
+
elif width > height:
|
| 191 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 192 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 193 |
+
return result
|
| 194 |
+
else:
|
| 195 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 196 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 197 |
+
return result
|
| 198 |
+
|
| 199 |
+
image = expand2square(image)
|
| 200 |
+
elif image_process_mode in ["Default", "Crop"]:
|
| 201 |
+
pass
|
| 202 |
+
elif image_process_mode == "Resize":
|
| 203 |
+
image = image.resize((336, 336))
|
| 204 |
+
else:
|
| 205 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 206 |
+
|
| 207 |
+
if type(image) is not Image.Image:
|
| 208 |
+
image = Image.open(image).convert("RGB")
|
| 209 |
+
|
| 210 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 211 |
+
aspect_ratio = max_hw / min_hw
|
| 212 |
+
max_len, min_len = 672, 448
|
| 213 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 214 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 215 |
+
W, H = image.size
|
| 216 |
+
if H > W:
|
| 217 |
+
H, W = longest_edge, shortest_edge
|
| 218 |
+
else:
|
| 219 |
+
H, W = shortest_edge, longest_edge
|
| 220 |
+
image = image.resize((W, H))
|
| 221 |
+
if return_pil:
|
| 222 |
+
return image
|
| 223 |
+
else:
|
| 224 |
+
buffered = BytesIO()
|
| 225 |
+
image.save(buffered, format=image_format)
|
| 226 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 227 |
+
return img_b64_str
|
| 228 |
+
|
| 229 |
+
def get_images(self, return_pil=False, return_path=False):
|
| 230 |
+
images = []
|
| 231 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
| 232 |
+
if i % 2 == 0:
|
| 233 |
+
if type(msg) is tuple:
|
| 234 |
+
msg, image, image_process_mode = msg
|
| 235 |
+
if type(image) != list:
|
| 236 |
+
image = [image]
|
| 237 |
+
for img in image:
|
| 238 |
+
if not return_path and self.is_image_file(img):
|
| 239 |
+
img = self.process_image(img, image_process_mode, return_pil=return_pil)
|
| 240 |
+
else:
|
| 241 |
+
images.append(img)
|
| 242 |
+
return images
|
| 243 |
+
|
| 244 |
+
def is_image_file(self, filename):
|
| 245 |
+
image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
|
| 246 |
+
return any(filename.lower().endswith(ext) for ext in image_extensions)
|
| 247 |
+
|
| 248 |
+
def is_video_file(self, filename):
|
| 249 |
+
video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
|
| 250 |
+
return any(filename.lower().endswith(ext) for ext in video_extensions)
|
| 251 |
+
|
| 252 |
+
def to_gradio_chatbot(self):
|
| 253 |
+
ret = []
|
| 254 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
| 255 |
+
if i % 2 == 0:
|
| 256 |
+
if type(msg) is tuple:
|
| 257 |
+
msg, image, image_process_mode = msg
|
| 258 |
+
if type(image) != list:
|
| 259 |
+
image = [image]
|
| 260 |
+
if len(image) == 1:
|
| 261 |
+
msg = "<image>\n" + msg.replace("<image>", "").strip()
|
| 262 |
+
else:
|
| 263 |
+
msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
|
| 264 |
+
|
| 265 |
+
img_str_list = []
|
| 266 |
+
for img in image:
|
| 267 |
+
if self.is_image_file(img):
|
| 268 |
+
img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
|
| 269 |
+
img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
|
| 270 |
+
img_str_list.append(img_str)
|
| 271 |
+
elif self.is_video_file(img):
|
| 272 |
+
ret.append(((img,), None))
|
| 273 |
+
|
| 274 |
+
msg = msg.strip()
|
| 275 |
+
img_place_holder = ""
|
| 276 |
+
for img_str in img_str_list:
|
| 277 |
+
img_place_holder += f"{img_str}\n\n"
|
| 278 |
+
|
| 279 |
+
if len(img_str_list) > 0:
|
| 280 |
+
msg = f"{img_place_holder}\n\n{msg}"
|
| 281 |
+
|
| 282 |
+
if len(msg) > 0:
|
| 283 |
+
ret.append([msg, None])
|
| 284 |
+
else:
|
| 285 |
+
ret.append([msg, None])
|
| 286 |
+
else:
|
| 287 |
+
ret[-1][-1] = msg
|
| 288 |
+
return ret
|
| 289 |
+
|
| 290 |
+
def copy(self):
|
| 291 |
+
return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
|
| 292 |
+
|
| 293 |
+
def dict(self):
|
| 294 |
+
if len(self.get_images()) > 0:
|
| 295 |
+
return {
|
| 296 |
+
"system": self.system,
|
| 297 |
+
"roles": self.roles,
|
| 298 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
| 299 |
+
"offset": self.offset,
|
| 300 |
+
"sep": self.sep,
|
| 301 |
+
"sep2": self.sep2,
|
| 302 |
+
}
|
| 303 |
+
return {
|
| 304 |
+
"system": self.system,
|
| 305 |
+
"roles": self.roles,
|
| 306 |
+
"messages": self.messages,
|
| 307 |
+
"offset": self.offset,
|
| 308 |
+
"sep": self.sep,
|
| 309 |
+
"sep2": self.sep2,
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
conv_vicuna_v0 = Conversation(
|
| 314 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 315 |
+
roles=("Human", "Assistant"),
|
| 316 |
+
messages=[
|
| 317 |
+
["Human", "What are the key differences between renewable and non-renewable energy sources?"],
|
| 318 |
+
[
|
| 319 |
+
"Assistant",
|
| 320 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
| 321 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
| 322 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
| 323 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
| 324 |
+
"renewable and non-renewable energy sources:\n"
|
| 325 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
| 326 |
+
"energy sources are finite and will eventually run out.\n"
|
| 327 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
| 328 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
| 329 |
+
"and other negative effects.\n"
|
| 330 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
| 331 |
+
"have lower operational costs than non-renewable sources.\n"
|
| 332 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
| 333 |
+
"locations than non-renewable sources.\n"
|
| 334 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
| 335 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
| 336 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
| 337 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
|
| 338 |
+
],
|
| 339 |
+
],
|
| 340 |
+
offset=2,
|
| 341 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 342 |
+
sep="###",
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
conv_vicuna_v1 = Conversation(
|
| 346 |
+
system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
| 347 |
+
roles=("USER", "ASSISTANT"),
|
| 348 |
+
version="v1",
|
| 349 |
+
messages=[],
|
| 350 |
+
offset=0,
|
| 351 |
+
sep_style=SeparatorStyle.TWO,
|
| 352 |
+
sep=" ",
|
| 353 |
+
sep2="</s>",
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
conv_llama_2 = Conversation(
|
| 357 |
+
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.
|
| 358 |
+
|
| 359 |
+
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.""",
|
| 360 |
+
roles=("USER", "ASSISTANT"),
|
| 361 |
+
version="llama_v2",
|
| 362 |
+
messages=[],
|
| 363 |
+
offset=0,
|
| 364 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 365 |
+
sep="<s>",
|
| 366 |
+
sep2="</s>",
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
conv_llava_llama_2 = Conversation(
|
| 370 |
+
system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
| 371 |
+
roles=("USER", "ASSISTANT"),
|
| 372 |
+
version="llama_v2",
|
| 373 |
+
messages=[],
|
| 374 |
+
offset=0,
|
| 375 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 376 |
+
sep="<s>",
|
| 377 |
+
sep2="</s>",
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def safe_load_tokenizer(tokenizer_id):
|
| 381 |
+
try:
|
| 382 |
+
return AutoTokenizer.from_pretrained(tokenizer_id)
|
| 383 |
+
except Exception:
|
| 384 |
+
return None
|
| 385 |
+
|
| 386 |
+
conv_llava_llama_3 = Conversation(
|
| 387 |
+
system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
|
| 388 |
+
roles=("user", "assistant"),
|
| 389 |
+
version="llama_v3",
|
| 390 |
+
messages=[],
|
| 391 |
+
offset=0,
|
| 392 |
+
sep="<|eot_id|>",
|
| 393 |
+
sep_style=SeparatorStyle.LLAMA_3,
|
| 394 |
+
tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 395 |
+
tokenizer=safe_load_tokenizer("meta-llama/Meta-Llama-3-8B-Instruct"),
|
| 396 |
+
stop_token_ids=[128009],
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
conv_mistral_instruct = Conversation(
|
| 400 |
+
system="",
|
| 401 |
+
roles=("USER", "ASSISTANT"),
|
| 402 |
+
version="llama_v2",
|
| 403 |
+
messages=[],
|
| 404 |
+
offset=0,
|
| 405 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 406 |
+
sep="",
|
| 407 |
+
sep2="</s>",
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
conv_llava_llama_2_simple = Conversation(
|
| 411 |
+
system="Answer the questions about the visual content that the user provides.",
|
| 412 |
+
roles=("USER", "ASSISTANT"),
|
| 413 |
+
version="llama_v2",
|
| 414 |
+
messages=[],
|
| 415 |
+
offset=0,
|
| 416 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 417 |
+
sep="<s>",
|
| 418 |
+
sep2="</s>",
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
conv_llava_llama_2_mmtag = Conversation(
|
| 422 |
+
system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 423 |
+
roles=("USER", "ASSISTANT"),
|
| 424 |
+
version="llama_v2_mmtag",
|
| 425 |
+
messages=[],
|
| 426 |
+
offset=0,
|
| 427 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 428 |
+
sep="<s>",
|
| 429 |
+
sep2="</s>",
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
conv_mpt = Conversation(
|
| 433 |
+
system="""<|im_start|>system
|
| 434 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
| 435 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 436 |
+
version="mpt",
|
| 437 |
+
messages=[],
|
| 438 |
+
offset=0,
|
| 439 |
+
sep_style=SeparatorStyle.MPT,
|
| 440 |
+
sep="<|im_end|>",
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
conv_qwen = Conversation(
|
| 444 |
+
system="""<|im_start|>system
|
| 445 |
+
You are a helpful assistant.""",
|
| 446 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
| 447 |
+
version="qwen",
|
| 448 |
+
messages=[],
|
| 449 |
+
offset=0,
|
| 450 |
+
sep_style=SeparatorStyle.CHATML,
|
| 451 |
+
sep="<|im_end|>",
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
|
| 455 |
+
|
| 456 |
+
conv_llava_plain = Conversation(
|
| 457 |
+
system="",
|
| 458 |
+
roles=("", ""),
|
| 459 |
+
messages=[],
|
| 460 |
+
offset=0,
|
| 461 |
+
sep_style=SeparatorStyle.PLAIN,
|
| 462 |
+
sep="\n",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
conv_llava_v0 = Conversation(
|
| 466 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 467 |
+
roles=("Human", "Assistant"),
|
| 468 |
+
messages=[],
|
| 469 |
+
offset=0,
|
| 470 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 471 |
+
sep="###",
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
conv_llava_v0_mmtag = Conversation(
|
| 475 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 476 |
+
"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."
|
| 477 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 478 |
+
roles=("Human", "Assistant"),
|
| 479 |
+
messages=[],
|
| 480 |
+
offset=0,
|
| 481 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 482 |
+
sep="###",
|
| 483 |
+
version="v0_mmtag",
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
conv_llava_v1 = Conversation(
|
| 487 |
+
system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 488 |
+
roles=("USER", "ASSISTANT"),
|
| 489 |
+
version="v1",
|
| 490 |
+
messages=[],
|
| 491 |
+
offset=0,
|
| 492 |
+
sep_style=SeparatorStyle.TWO,
|
| 493 |
+
sep=" ",
|
| 494 |
+
sep2="</s>",
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
conv_llava_v1_mmtag = Conversation(
|
| 498 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 499 |
+
"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."
|
| 500 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 501 |
+
roles=("USER", "ASSISTANT"),
|
| 502 |
+
messages=[],
|
| 503 |
+
offset=0,
|
| 504 |
+
sep_style=SeparatorStyle.TWO,
|
| 505 |
+
sep=" ",
|
| 506 |
+
sep2="</s>",
|
| 507 |
+
version="v1_mmtag",
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
conv_mistral_orca = Conversation(
|
| 511 |
+
system="""<|im_start|>system
|
| 512 |
+
You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
|
| 513 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 514 |
+
version="mpt",
|
| 515 |
+
messages=[],
|
| 516 |
+
offset=0,
|
| 517 |
+
sep_style=SeparatorStyle.MPT,
|
| 518 |
+
sep="<|im_end|>",
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
conv_mistral_zephyr = Conversation(
|
| 522 |
+
system="""<|system|>
|
| 523 |
+
You are a helpful AI assistant.""",
|
| 524 |
+
roles=("<|user|>\n", "<|assistant|>\n"),
|
| 525 |
+
version="mpt",
|
| 526 |
+
messages=[],
|
| 527 |
+
offset=0,
|
| 528 |
+
sep_style=SeparatorStyle.MPT,
|
| 529 |
+
sep="</s>",
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
conv_mistral_direct = Conversation(
|
| 533 |
+
system="""<|im_start|>system
|
| 534 |
+
Answer the questions.""",
|
| 535 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 536 |
+
version="mpt",
|
| 537 |
+
messages=[],
|
| 538 |
+
offset=0,
|
| 539 |
+
sep_style=SeparatorStyle.MPT,
|
| 540 |
+
sep="<|im_end|>",
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
conv_chatml_direct = Conversation(
|
| 544 |
+
system="""<|im_start|>system
|
| 545 |
+
Answer the questions.""",
|
| 546 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 547 |
+
version="mpt",
|
| 548 |
+
messages=[],
|
| 549 |
+
offset=0,
|
| 550 |
+
sep_style=SeparatorStyle.MPT,
|
| 551 |
+
sep="<|im_end|>",
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
default_conversation = conv_vicuna_v0
|
| 555 |
+
conv_templates = {
|
| 556 |
+
"default": conv_vicuna_v0,
|
| 557 |
+
"v0": conv_vicuna_v0,
|
| 558 |
+
"v1": conv_vicuna_v1,
|
| 559 |
+
"vicuna_v1": conv_vicuna_v1,
|
| 560 |
+
"llama_2": conv_llama_2,
|
| 561 |
+
"mistral_instruct": conv_mistral_instruct,
|
| 562 |
+
"mistral_orca": conv_mistral_orca,
|
| 563 |
+
"mistral_zephyr": conv_mistral_zephyr,
|
| 564 |
+
"mistral_direct": conv_mistral_direct,
|
| 565 |
+
"plain": conv_llava_plain,
|
| 566 |
+
"v0_plain": conv_llava_plain,
|
| 567 |
+
"chatml_direct": conv_chatml_direct,
|
| 568 |
+
"llava_v0": conv_llava_v0,
|
| 569 |
+
"llava_v0_mmtag": conv_llava_v0_mmtag,
|
| 570 |
+
"llava_v1": conv_llava_v1,
|
| 571 |
+
"llava_v1_mmtag": conv_llava_v1_mmtag,
|
| 572 |
+
"llava_llama_2": conv_llava_llama_2,
|
| 573 |
+
"llava_llama_3": conv_llava_llama_3,
|
| 574 |
+
"llava_llama_2_simple": conv_llava_llama_2_simple,
|
| 575 |
+
"llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
|
| 576 |
+
"llava_mistral_instruct": conv_mistral_instruct,
|
| 577 |
+
"mpt": conv_mpt,
|
| 578 |
+
"qwen_1_5": conv_qwen,
|
| 579 |
+
"qwen_2": conv_qwen,
|
| 580 |
+
"gemma_instruct": conv_gemma_instruct,
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
if __name__ == "__main__":
|
| 585 |
+
print(default_conversation.get_prompt())
|
spatial-model/VLM-3R/llava/eval/eval_sqa3d.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import string
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
def clean_answer(data):
|
| 8 |
+
data = data.lower()
|
| 9 |
+
data = re.sub('[ ]+$' ,'', data)
|
| 10 |
+
data = re.sub('^[ ]+' ,'', data)
|
| 11 |
+
data = re.sub(' {2,}', ' ', data)
|
| 12 |
+
|
| 13 |
+
data = re.sub('\.[ ]{2,}', '. ', data)
|
| 14 |
+
data = re.sub('[^a-zA-Z0-9,\'\s\-:]+', '', data)
|
| 15 |
+
data = re.sub('ç' ,'c', data)
|
| 16 |
+
data = re.sub('’' ,'\'', data)
|
| 17 |
+
data = re.sub(r'\bletf\b' ,'left', data)
|
| 18 |
+
data = re.sub(r'\blet\b' ,'left', data)
|
| 19 |
+
data = re.sub(r'\btehre\b' ,'there', data)
|
| 20 |
+
data = re.sub(r'\brigth\b' ,'right', data)
|
| 21 |
+
data = re.sub(r'\brght\b' ,'right', data)
|
| 22 |
+
data = re.sub(r'\bbehine\b', 'behind', data)
|
| 23 |
+
data = re.sub(r'\btv\b' ,'TV', data)
|
| 24 |
+
data = re.sub(r'\bchai\b' ,'chair', data)
|
| 25 |
+
data = re.sub(r'\bwasing\b' ,'washing', data)
|
| 26 |
+
data = re.sub(r'\bwaslked\b' ,'walked', data)
|
| 27 |
+
data = re.sub(r'\boclock\b' ,'o\'clock', data)
|
| 28 |
+
data = re.sub(r'\bo\'[ ]+clock\b' ,'o\'clock', data)
|
| 29 |
+
|
| 30 |
+
# digit to word, only for answer
|
| 31 |
+
data = re.sub(r'\b0\b', 'zero', data)
|
| 32 |
+
data = re.sub(r'\bnone\b', 'zero', data)
|
| 33 |
+
data = re.sub(r'\b1\b', 'one', data)
|
| 34 |
+
data = re.sub(r'\b2\b', 'two', data)
|
| 35 |
+
data = re.sub(r'\b3\b', 'three', data)
|
| 36 |
+
data = re.sub(r'\b4\b', 'four', data)
|
| 37 |
+
data = re.sub(r'\b5\b', 'five', data)
|
| 38 |
+
data = re.sub(r'\b6\b', 'six', data)
|
| 39 |
+
data = re.sub(r'\b7\b', 'seven', data)
|
| 40 |
+
data = re.sub(r'\b8\b', 'eight', data)
|
| 41 |
+
data = re.sub(r'\b9\b', 'nine', data)
|
| 42 |
+
data = re.sub(r'\b10\b', 'ten', data)
|
| 43 |
+
data = re.sub(r'\b11\b', 'eleven', data)
|
| 44 |
+
data = re.sub(r'\b12\b', 'twelve', data)
|
| 45 |
+
data = re.sub(r'\b13\b', 'thirteen', data)
|
| 46 |
+
data = re.sub(r'\b14\b', 'fourteen', data)
|
| 47 |
+
data = re.sub(r'\b15\b', 'fifteen', data)
|
| 48 |
+
data = re.sub(r'\b16\b', 'sixteen', data)
|
| 49 |
+
data = re.sub(r'\b17\b', 'seventeen', data)
|
| 50 |
+
data = re.sub(r'\b18\b', 'eighteen', data)
|
| 51 |
+
data = re.sub(r'\b19\b', 'nineteen', data)
|
| 52 |
+
data = re.sub(r'\b20\b', 'twenty', data)
|
| 53 |
+
data = re.sub(r'\b23\b', 'twenty-three', data)
|
| 54 |
+
|
| 55 |
+
# misc
|
| 56 |
+
# no1, mat2, etc
|
| 57 |
+
data = re.sub(r'\b([a-zA-Z]+)([0-9])\b' ,r'\g<1>', data)
|
| 58 |
+
data = re.sub(r'\ba\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 59 |
+
data = re.sub(r'\ban\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 60 |
+
data = re.sub(r'\bthe\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 61 |
+
|
| 62 |
+
data = re.sub(r'\bbackwards\b', 'backward', data)
|
| 63 |
+
|
| 64 |
+
return data
|
| 65 |
+
|
| 66 |
+
def main(args):
|
| 67 |
+
with open(args.input_file) as f:
|
| 68 |
+
data = [json.loads(line.strip()) for line in f.readlines()]
|
| 69 |
+
|
| 70 |
+
if args.n != -1:
|
| 71 |
+
data = data[:args.n]
|
| 72 |
+
|
| 73 |
+
from collections import defaultdict
|
| 74 |
+
correct_per_type = defaultdict(list)
|
| 75 |
+
|
| 76 |
+
for item in data:
|
| 77 |
+
pred = clean_answer(item['pred_response'])
|
| 78 |
+
gt = clean_answer(item['gt_response'])
|
| 79 |
+
|
| 80 |
+
correct_per_type["all"].append(int(pred == gt))
|
| 81 |
+
correct_per_type[item['question_type']].append(int(pred == gt))
|
| 82 |
+
|
| 83 |
+
for k in correct_per_type:
|
| 84 |
+
print(f"{k}: {np.mean(correct_per_type[k]) * 100}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__=="__main__":
|
| 88 |
+
parser = argparse.ArgumentParser()
|
| 89 |
+
parser.add_argument('--input-file', type=str, default='results/llava_next_video_sqa3d_test_answer_pred_scanqa_sqa3d.jsonl')
|
| 90 |
+
parser.add_argument("-n", type=int, default=-1)
|
| 91 |
+
args = parser.parse_args()
|
| 92 |
+
|
| 93 |
+
main(args)
|
spatial-model/VLM-3R/llava/eval/evaluate_interleave.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from rouge import Rouge
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
spot_the_diff = ["Spot-the-Diff", "Birds-to-Words", "CLEVR-Change"]
|
| 12 |
+
image_edit_instruct = ["IEdit", "HQ-Edit", "MagicBrush"]
|
| 13 |
+
visual_story_telling = ["AESOP", "FlintstonesSV", "PororoSV", "VIST"]
|
| 14 |
+
visual_cloze = ["COMICS_Dialogue", "RecipeQA_VisualCloze"]
|
| 15 |
+
text_rich_vqa = ["WebQA", "TQA", "OCR-VQA", "DocVQA"]
|
| 16 |
+
multi_image_vqa = ["MIT-States_StateCoherence", "MIT-States_PropertyCoherence", "VISION", "RecipeQA_ImageCoherence"]
|
| 17 |
+
|
| 18 |
+
puzzle = ["RAVEN"]
|
| 19 |
+
nlrv2 = ["NLVR2_Mantis"]
|
| 20 |
+
qbench = ["QBench"]
|
| 21 |
+
|
| 22 |
+
class Eval:
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)")
|
| 25 |
+
self.commaStrip = re.compile("(\d)(\,)(\d)")
|
| 26 |
+
self.punct = [
|
| 27 |
+
";",
|
| 28 |
+
r"/",
|
| 29 |
+
"[",
|
| 30 |
+
"]",
|
| 31 |
+
'"',
|
| 32 |
+
"{",
|
| 33 |
+
"}",
|
| 34 |
+
"(",
|
| 35 |
+
")",
|
| 36 |
+
"=",
|
| 37 |
+
"+",
|
| 38 |
+
"\\",
|
| 39 |
+
"_",
|
| 40 |
+
"-",
|
| 41 |
+
">",
|
| 42 |
+
"<",
|
| 43 |
+
"@",
|
| 44 |
+
"`",
|
| 45 |
+
",",
|
| 46 |
+
"?",
|
| 47 |
+
"!",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
def processPunctuation(self, inText):
|
| 51 |
+
outText = inText
|
| 52 |
+
for p in self.punct:
|
| 53 |
+
if (p + " " in inText or " " + p in inText) or (
|
| 54 |
+
re.search(self.commaStrip, inText) != None
|
| 55 |
+
):
|
| 56 |
+
outText = outText.replace(p, "")
|
| 57 |
+
else:
|
| 58 |
+
outText = outText.replace(p, " ")
|
| 59 |
+
outText = self.periodStrip.sub("", outText, re.UNICODE)
|
| 60 |
+
return outText
|
| 61 |
+
|
| 62 |
+
def process(self, answer):
|
| 63 |
+
answer = answer.replace("\n", " ")
|
| 64 |
+
answer = answer.replace("\t", " ")
|
| 65 |
+
answer = answer.strip()
|
| 66 |
+
answer = self.processPunctuation(answer)
|
| 67 |
+
answer = answer.strip('\'')
|
| 68 |
+
answer = answer.strip('\"')
|
| 69 |
+
answer = answer.strip(')')
|
| 70 |
+
answer = answer.strip('(')
|
| 71 |
+
answer = answer.strip().lower()
|
| 72 |
+
return answer
|
| 73 |
+
|
| 74 |
+
def evaluate_rouge(self,preds):
|
| 75 |
+
rouge = Rouge()
|
| 76 |
+
acc = {'f': []}
|
| 77 |
+
eval_list = []
|
| 78 |
+
for i, res in enumerate(preds):
|
| 79 |
+
sample_id = res['sample_id']
|
| 80 |
+
# print(sample_id)
|
| 81 |
+
gt_ans = self.process(res["gt_response"])
|
| 82 |
+
pred_ans = self.process(res["pred_response"])
|
| 83 |
+
# assert gt_ans != ''
|
| 84 |
+
|
| 85 |
+
if gt_ans == '':
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
if pred_ans == '':
|
| 89 |
+
s = 0
|
| 90 |
+
else:
|
| 91 |
+
if len(pred_ans) > 512:
|
| 92 |
+
pred_ans = pred_ans[0: 512]
|
| 93 |
+
s = rouge.get_scores(pred_ans, gt_ans)[0]['rouge-l']['f']
|
| 94 |
+
acc['f'].append(s)
|
| 95 |
+
eval_list.append({'id':str(sample_id),'score':str(round(s,3))})
|
| 96 |
+
results = {'Rouge-L f': np.mean(acc['f'])}
|
| 97 |
+
return results,eval_list
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def judge_multi_choice(self,sample):
|
| 101 |
+
sample_id = sample['sample_id']
|
| 102 |
+
gt_ans = sample["gt_response"]
|
| 103 |
+
pred_ans = sample["pred_response"]
|
| 104 |
+
|
| 105 |
+
if ":" in pred_ans:
|
| 106 |
+
a_list = pred_ans.split(":")
|
| 107 |
+
a_list = [a.strip() for a in a_list ]
|
| 108 |
+
for a in a_list:
|
| 109 |
+
if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
|
| 110 |
+
pred_ans = a
|
| 111 |
+
|
| 112 |
+
if pred_ans == gt_ans:
|
| 113 |
+
return 1
|
| 114 |
+
else:
|
| 115 |
+
return 0
|
| 116 |
+
|
| 117 |
+
def process_sample(self,sample):
|
| 118 |
+
sample["gt_response"] = self.process(sample["gt_response"])
|
| 119 |
+
sample["pred_response"] = self.process(sample["pred_response"])
|
| 120 |
+
|
| 121 |
+
def evaluate_multichoice(self, preditions):
|
| 122 |
+
correct = 0
|
| 123 |
+
eval_list = []
|
| 124 |
+
for i, sample in enumerate(preditions):
|
| 125 |
+
self.process_sample(sample)
|
| 126 |
+
score = self.judge_multi_choice(sample)
|
| 127 |
+
sample_id = sample['sample_id']
|
| 128 |
+
sample['result'] = score
|
| 129 |
+
eval_list.append({'id':str(sample_id),'score':str(score)})
|
| 130 |
+
correct+=score
|
| 131 |
+
return {'Accuracy':correct/len(preditions)},eval_list
|
| 132 |
+
|
| 133 |
+
def evaluate_multi_choice_image(self,preditions):
|
| 134 |
+
correct = 0
|
| 135 |
+
eval_list = []
|
| 136 |
+
for i,sample in enumerate(preditions):
|
| 137 |
+
gt_ans = self.process(sample["gt_response"])
|
| 138 |
+
pred_ans = self.process(sample["pred_response"])
|
| 139 |
+
sample_id = sample['sample_id']
|
| 140 |
+
|
| 141 |
+
if ":" in pred_ans:
|
| 142 |
+
a_list = pred_ans.split(":")
|
| 143 |
+
a_list = [a.strip() for a in a_list ]
|
| 144 |
+
for a in a_list:
|
| 145 |
+
if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
|
| 146 |
+
pred_ans = a
|
| 147 |
+
|
| 148 |
+
if gt_ans == pred_ans:
|
| 149 |
+
score = 1
|
| 150 |
+
else:
|
| 151 |
+
score = 0
|
| 152 |
+
sample_id = sample['sample_id']
|
| 153 |
+
sample['result'] = score
|
| 154 |
+
eval_list.append({'id':str(sample_id),'score':str(score)})
|
| 155 |
+
correct+=score
|
| 156 |
+
return {'Accuracy':correct/len(preditions)},eval_list
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
parser = argparse.ArgumentParser()
|
| 161 |
+
parser.add_argument('--result-dir', type=str, required=True)
|
| 162 |
+
|
| 163 |
+
args = parser.parse_args()
|
| 164 |
+
|
| 165 |
+
result_file = os.path.join(args.result_dir, "result.jsonl")
|
| 166 |
+
|
| 167 |
+
if not os.path.exists(result_file):
|
| 168 |
+
print('No prediction file found')
|
| 169 |
+
exit(0)
|
| 170 |
+
with open(result_file, 'r') as f:
|
| 171 |
+
preds_all = [json.loads(line) for line in f]
|
| 172 |
+
|
| 173 |
+
preds_all_dict = dict()
|
| 174 |
+
for pred in preds_all:
|
| 175 |
+
if pred["dataset"] not in preds_all_dict:
|
| 176 |
+
preds_all_dict[pred["dataset"]] = list()
|
| 177 |
+
preds_all_dict[pred["dataset"]].append(pred)
|
| 178 |
+
|
| 179 |
+
image_choice_dataset_list = ["recipeqa-RecipeQA_VisualCloze", "RecipeQA_ImageCoherence", "COMICS_Panel"]
|
| 180 |
+
E = Eval()
|
| 181 |
+
|
| 182 |
+
eval_result_list = dict()
|
| 183 |
+
eval_result_list_detail = dict()
|
| 184 |
+
|
| 185 |
+
for dataset in preds_all_dict:
|
| 186 |
+
|
| 187 |
+
preds = preds_all_dict[dataset]
|
| 188 |
+
question_type = preds[0]["question_type"]
|
| 189 |
+
|
| 190 |
+
if question_type == 'open-ended':
|
| 191 |
+
eval_result, eval_list = E.evaluate_rouge(preds)
|
| 192 |
+
|
| 193 |
+
elif question_type == 'multi-choice' or dataset == 'nlrv2':
|
| 194 |
+
if dataset in image_choice_dataset_list:
|
| 195 |
+
eval_result, eval_list = E.evaluate_multi_choice_image(preds)
|
| 196 |
+
else:
|
| 197 |
+
eval_result, eval_list = E.evaluate_multichoice(preds)
|
| 198 |
+
|
| 199 |
+
else:
|
| 200 |
+
eval_result = 'Dataset not supported'
|
| 201 |
+
print('Dataset not supported')
|
| 202 |
+
exit(0)
|
| 203 |
+
|
| 204 |
+
print(dataset, end = ': ')
|
| 205 |
+
print(eval_result)
|
| 206 |
+
|
| 207 |
+
eval_result_list[dataset] = eval_result
|
| 208 |
+
eval_result_list_detail[dataset] = eval_list
|
| 209 |
+
|
| 210 |
+
os.makedirs(args.result_dir, exist_ok=True)
|
| 211 |
+
with open(os.path.join(args.result_dir, 'eval_dataset.json'), 'w') as f:
|
| 212 |
+
json.dump(eval_result_list, f, indent=4)
|
| 213 |
+
|
| 214 |
+
with open(os.path.join(args.result_dir,'eval_dataset_details.json'), 'w') as f:
|
| 215 |
+
json.dump(eval_result_list_detail, f, indent=4)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
eval_cat_list = dict()
|
| 219 |
+
print()
|
| 220 |
+
|
| 221 |
+
# spot_the_diff
|
| 222 |
+
score = 0
|
| 223 |
+
count = 0
|
| 224 |
+
for dataset in eval_result_list:
|
| 225 |
+
if dataset in spot_the_diff:
|
| 226 |
+
count += 1
|
| 227 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 228 |
+
if count > 0:
|
| 229 |
+
score /= count
|
| 230 |
+
eval_cat_list["spot_the_diff"] = score
|
| 231 |
+
print("spot_the_diff", end = ': ')
|
| 232 |
+
print('{:.2f}'.format(100 * score))
|
| 233 |
+
|
| 234 |
+
# image_edit_instruct
|
| 235 |
+
score = 0
|
| 236 |
+
count = 0
|
| 237 |
+
for dataset in eval_result_list:
|
| 238 |
+
if dataset in image_edit_instruct:
|
| 239 |
+
count += 1
|
| 240 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 241 |
+
if count > 0:
|
| 242 |
+
score /= count
|
| 243 |
+
eval_cat_list["image_edit_instruct"] = score
|
| 244 |
+
print("image_edit_instruct", end = ': ')
|
| 245 |
+
print('{:.2f}'.format(100 * score))
|
| 246 |
+
|
| 247 |
+
# visual_story_telling
|
| 248 |
+
score = 0
|
| 249 |
+
count = 0
|
| 250 |
+
for dataset in eval_result_list:
|
| 251 |
+
if dataset in visual_story_telling:
|
| 252 |
+
count += 1
|
| 253 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 254 |
+
if count > 0:
|
| 255 |
+
score /= count
|
| 256 |
+
eval_cat_list["visual_story_telling"] = score
|
| 257 |
+
print("visual_story_telling", end = ': ')
|
| 258 |
+
print('{:.2f}'.format(100 * score))
|
| 259 |
+
|
| 260 |
+
# visual_cloze
|
| 261 |
+
score = 0
|
| 262 |
+
count = 0
|
| 263 |
+
for dataset in eval_result_list:
|
| 264 |
+
if dataset in visual_cloze:
|
| 265 |
+
count += 1
|
| 266 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 267 |
+
if count > 0:
|
| 268 |
+
score /= count
|
| 269 |
+
eval_cat_list["visual_cloze"] = score
|
| 270 |
+
print("visual_cloze", end = ': ')
|
| 271 |
+
print('{:.2f}'.format(100 * score))
|
| 272 |
+
|
| 273 |
+
# text_rich_vqa
|
| 274 |
+
score = 0
|
| 275 |
+
count = 0
|
| 276 |
+
for dataset in eval_result_list:
|
| 277 |
+
if dataset in text_rich_vqa:
|
| 278 |
+
count += 1
|
| 279 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 280 |
+
if count > 0:
|
| 281 |
+
score /= count
|
| 282 |
+
eval_cat_list["text_rich_vqa"] = score
|
| 283 |
+
print("text_rich_vqa", end = ': ')
|
| 284 |
+
print('{:.2f}'.format(100 * score))
|
| 285 |
+
|
| 286 |
+
# multi_image_vqa
|
| 287 |
+
score = 0
|
| 288 |
+
count = 0
|
| 289 |
+
for dataset in eval_result_list:
|
| 290 |
+
if dataset in multi_image_vqa:
|
| 291 |
+
count += 1
|
| 292 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 293 |
+
if count > 0:
|
| 294 |
+
score /= count
|
| 295 |
+
eval_cat_list["multi_image_vqa"] = score
|
| 296 |
+
print("multi_image_vqa", end = ': ')
|
| 297 |
+
print('{:.2f}'.format(100 * score))
|
| 298 |
+
|
| 299 |
+
# puzzle
|
| 300 |
+
score = 0
|
| 301 |
+
count = 0
|
| 302 |
+
for dataset in eval_result_list:
|
| 303 |
+
if dataset in puzzle:
|
| 304 |
+
count += 1
|
| 305 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 306 |
+
if count > 0:
|
| 307 |
+
score /= count
|
| 308 |
+
eval_cat_list["puzzle"] = score
|
| 309 |
+
print("puzzle", end = ': ')
|
| 310 |
+
print('{:.2f}'.format(100 * score))
|
| 311 |
+
|
| 312 |
+
# nlrv2
|
| 313 |
+
score = 0
|
| 314 |
+
count = 0
|
| 315 |
+
for dataset in eval_result_list:
|
| 316 |
+
if dataset in nlrv2:
|
| 317 |
+
count += 1
|
| 318 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 319 |
+
if count > 0:
|
| 320 |
+
score /= count
|
| 321 |
+
eval_cat_list["nlrv2"] = score
|
| 322 |
+
print("nlrv2", end = ': ')
|
| 323 |
+
print('{:.2f}'.format(100 * score))
|
| 324 |
+
|
| 325 |
+
# qbench
|
| 326 |
+
score = 0
|
| 327 |
+
count = 0
|
| 328 |
+
for dataset in eval_result_list:
|
| 329 |
+
if dataset in qbench:
|
| 330 |
+
count += 1
|
| 331 |
+
score += list(eval_result_list[dataset].values())[0]
|
| 332 |
+
if count > 0:
|
| 333 |
+
score /= count
|
| 334 |
+
eval_cat_list["qbench"] = score
|
| 335 |
+
print("qbench", end = ': ')
|
| 336 |
+
print('{:.2f}'.format(100 * score))
|
| 337 |
+
|
| 338 |
+
with open(os.path.join(args.result_dir,'eval_cat.json'), 'w') as f:
|
| 339 |
+
json.dump(eval_cat_list, f, indent=4)
|
spatial-model/VLM-3R/llava/eval/model_scanqa.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 13 |
+
|
| 14 |
+
from PIL import Image
|
| 15 |
+
import math
|
| 16 |
+
from llava.eval.model_vqa import preprocess_qwen
|
| 17 |
+
|
| 18 |
+
from decord import VideoReader, cpu
|
| 19 |
+
import numpy as np
|
| 20 |
+
import warnings
|
| 21 |
+
warnings.filterwarnings("ignore")
|
| 22 |
+
import copy
|
| 23 |
+
|
| 24 |
+
def load_video(video_path, max_frames_num,fps=1,force_sample=False):
|
| 25 |
+
if max_frames_num == 0:
|
| 26 |
+
return np.zeros((1, 336, 336, 3))
|
| 27 |
+
vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
|
| 28 |
+
total_frame_num = len(vr)
|
| 29 |
+
video_time = total_frame_num / vr.get_avg_fps()
|
| 30 |
+
fps = round(vr.get_avg_fps()/fps)
|
| 31 |
+
frame_idx = [i for i in range(0, len(vr), fps)]
|
| 32 |
+
frame_time = [i/fps for i in frame_idx]
|
| 33 |
+
if len(frame_idx) > max_frames_num or force_sample:
|
| 34 |
+
sample_fps = max_frames_num
|
| 35 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
|
| 36 |
+
frame_idx = uniform_sampled_frames.tolist()
|
| 37 |
+
frame_time = [i/vr.get_avg_fps() for i in frame_idx]
|
| 38 |
+
frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
|
| 39 |
+
spare_frames = vr.get_batch(frame_idx).asnumpy()
|
| 40 |
+
# import pdb;pdb.set_trace()
|
| 41 |
+
return spare_frames,frame_time,video_time
|
| 42 |
+
|
| 43 |
+
def split_list(lst, n):
|
| 44 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
| 45 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
| 46 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_chunk(lst, n, k):
|
| 50 |
+
chunks = split_list(lst, n)
|
| 51 |
+
return chunks[k]
|
| 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 = "llava_qwen_lora"
|
| 59 |
+
tokenizer, model, processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, torch_dtype="bfloat16")
|
| 60 |
+
model.to(device="cuda")
|
| 61 |
+
# questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
|
| 62 |
+
with open(args.question_file, 'r') as file:
|
| 63 |
+
questions = json.load(file)
|
| 64 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
| 65 |
+
answers_file = os.path.expanduser(args.answers_file)
|
| 66 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
| 67 |
+
ans_file = open(answers_file, "w")
|
| 68 |
+
for line in tqdm(questions):
|
| 69 |
+
idx = line["question_id"]
|
| 70 |
+
scene_id = line["scene_id"]
|
| 71 |
+
video_path = os.path.join(args.video_folder, f"{scene_id}.mp4")
|
| 72 |
+
qs = line["question"]
|
| 73 |
+
|
| 74 |
+
args.conv_mode = "qwen_1_5"
|
| 75 |
+
|
| 76 |
+
# load video
|
| 77 |
+
video,frame_time,video_time = load_video(video_path, args.max_frames_num, 1, force_sample=True)
|
| 78 |
+
video = processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
|
| 79 |
+
video = [video]
|
| 80 |
+
time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
|
| 81 |
+
question = DEFAULT_IMAGE_TOKEN + f"{time_instruciton}\n{qs}\nAnswer the question simply."
|
| 82 |
+
|
| 83 |
+
conv = copy.deepcopy(conv_templates[args.conv_mode])
|
| 84 |
+
conv.append_message(conv.roles[0], question)
|
| 85 |
+
conv.append_message(conv.roles[1], None)
|
| 86 |
+
prompt_question = conv.get_prompt()
|
| 87 |
+
|
| 88 |
+
input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(args.device)
|
| 89 |
+
|
| 90 |
+
with torch.inference_mode():
|
| 91 |
+
output_ids = model.generate(
|
| 92 |
+
input_ids,
|
| 93 |
+
images=video,
|
| 94 |
+
modalities= ["video"],
|
| 95 |
+
do_sample=True if args.temperature > 0 else False,
|
| 96 |
+
temperature=args.temperature,
|
| 97 |
+
top_p=args.top_p,
|
| 98 |
+
num_beams=args.num_beams,
|
| 99 |
+
max_new_tokens=512,
|
| 100 |
+
use_cache=True,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 104 |
+
|
| 105 |
+
ans_id = shortuuid.uuid()
|
| 106 |
+
ans_file.write(json.dumps({"question_id": idx,
|
| 107 |
+
"prompt": prompt_question,
|
| 108 |
+
"text": outputs,
|
| 109 |
+
"answer_id": ans_id,
|
| 110 |
+
"model_id": model_name,
|
| 111 |
+
"metadata": {}}) + "\n")
|
| 112 |
+
ans_file.flush()
|
| 113 |
+
ans_file.close()
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
parser = argparse.ArgumentParser()
|
| 117 |
+
parser.add_argument("--model-path", type=str, default="checkpoints/llava3d-v1.5-7b-task-v3-tuning")
|
| 118 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 119 |
+
parser.add_argument("--video-folder", type=str, default="playground/data/LLaVA-3D-Pretrain")
|
| 120 |
+
parser.add_argument("--question-file", type=str, default="playground/data/annotations/llava3d_sqa3d_val_question.json")
|
| 121 |
+
parser.add_argument("--answers-file", type=str, default="./llava3d_sqa3d_val_answer_pred.json")
|
| 122 |
+
parser.add_argument("--max-frames-num", type=int, default=32)
|
| 123 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 124 |
+
parser.add_argument("--extra-prompt", type=str, default="")
|
| 125 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
| 126 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
| 127 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
| 128 |
+
parser.add_argument("--temperature", type=float, default=0.)
|
| 129 |
+
parser.add_argument("--top_p", type=float, default=None)
|
| 130 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
| 131 |
+
args = parser.parse_args()
|
| 132 |
+
|
| 133 |
+
eval_model(args)
|
spatial-model/VLM-3R/llava/eval/model_sqa3d.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 13 |
+
|
| 14 |
+
from PIL import Image
|
| 15 |
+
import math
|
| 16 |
+
from llava.eval.model_vqa import preprocess_qwen
|
| 17 |
+
|
| 18 |
+
from decord import VideoReader, cpu
|
| 19 |
+
import numpy as np
|
| 20 |
+
import warnings
|
| 21 |
+
warnings.filterwarnings("ignore")
|
| 22 |
+
import copy
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_video(video_path, max_frames_num,fps=1,force_sample=False):
|
| 26 |
+
if max_frames_num == 0:
|
| 27 |
+
return np.zeros((1, 336, 336, 3))
|
| 28 |
+
vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
|
| 29 |
+
total_frame_num = len(vr)
|
| 30 |
+
video_time = total_frame_num / vr.get_avg_fps()
|
| 31 |
+
fps = round(vr.get_avg_fps()/fps)
|
| 32 |
+
frame_idx = [i for i in range(0, len(vr), fps)]
|
| 33 |
+
frame_time = [i/fps for i in frame_idx]
|
| 34 |
+
if len(frame_idx) > max_frames_num or force_sample:
|
| 35 |
+
sample_fps = max_frames_num
|
| 36 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
|
| 37 |
+
frame_idx = uniform_sampled_frames.tolist()
|
| 38 |
+
frame_time = [i/vr.get_avg_fps() for i in frame_idx]
|
| 39 |
+
frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
|
| 40 |
+
spare_frames = vr.get_batch(frame_idx).asnumpy()
|
| 41 |
+
# import pdb;pdb.set_trace()
|
| 42 |
+
return spare_frames,frame_time,video_time
|
| 43 |
+
|
| 44 |
+
def split_list(lst, n):
|
| 45 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
| 46 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
| 47 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_chunk(lst, n, k):
|
| 51 |
+
chunks = split_list(lst, n)
|
| 52 |
+
return chunks[k]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def eval_model(args):
|
| 56 |
+
# Model
|
| 57 |
+
disable_torch_init()
|
| 58 |
+
model_path = os.path.expanduser(args.model_path)
|
| 59 |
+
model_name = "llava_qwen_lora"
|
| 60 |
+
tokenizer, model, processor, context_len = load_pretrained_model(model_path, args.model_base, model_name, torch_dtype="bfloat16")
|
| 61 |
+
model.to(device="cuda")
|
| 62 |
+
|
| 63 |
+
# Load questions
|
| 64 |
+
with open(args.question_file, 'r') as file:
|
| 65 |
+
questions = json.load(file)
|
| 66 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
| 67 |
+
|
| 68 |
+
answers_file = os.path.expanduser(args.answer_file)
|
| 69 |
+
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
|
| 70 |
+
ans_file = open(answers_file, "w")
|
| 71 |
+
|
| 72 |
+
for line in tqdm(questions):
|
| 73 |
+
idx = line["id"]
|
| 74 |
+
question_type = line["metadata"]["question_type"]
|
| 75 |
+
dataset_name = line["metadata"]["dataset"]
|
| 76 |
+
video_id = line["video"].split("/")[-1]
|
| 77 |
+
|
| 78 |
+
# Get video path - assuming video files are in video_folder with .mp4 extension
|
| 79 |
+
video_path = os.path.join(args.video_folder, f"{video_id}.mp4")
|
| 80 |
+
|
| 81 |
+
gt = line["conversations"][1]["value"]
|
| 82 |
+
qs = line["conversations"][0]["value"].replace("<image>", "")
|
| 83 |
+
|
| 84 |
+
args.conv_mode = "qwen_1_5"
|
| 85 |
+
|
| 86 |
+
# Load video
|
| 87 |
+
video, frame_time, video_time = load_video(video_path, args.max_frame_num, 1, force_sample=True)
|
| 88 |
+
video = processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
|
| 89 |
+
video = [video]
|
| 90 |
+
|
| 91 |
+
time_instruction = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
|
| 92 |
+
question = DEFAULT_IMAGE_TOKEN + f"{time_instruction}\n{qs}"
|
| 93 |
+
|
| 94 |
+
conv = copy.deepcopy(conv_templates[args.conv_mode])
|
| 95 |
+
conv.append_message(conv.roles[0], question)
|
| 96 |
+
conv.append_message(conv.roles[1], None)
|
| 97 |
+
prompt_question = conv.get_prompt()
|
| 98 |
+
|
| 99 |
+
input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(args.device)
|
| 100 |
+
|
| 101 |
+
with torch.inference_mode():
|
| 102 |
+
output_ids = model.generate(
|
| 103 |
+
input_ids,
|
| 104 |
+
images=video,
|
| 105 |
+
modalities=["video"],
|
| 106 |
+
do_sample=True if args.temperature > 0 else False,
|
| 107 |
+
temperature=args.temperature,
|
| 108 |
+
top_p=args.top_p,
|
| 109 |
+
num_beams=args.num_beams,
|
| 110 |
+
max_new_tokens=512,
|
| 111 |
+
use_cache=True,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 115 |
+
|
| 116 |
+
ans_id = shortuuid.uuid()
|
| 117 |
+
ans_file.write(json.dumps({
|
| 118 |
+
"dataset": dataset_name,
|
| 119 |
+
"sample_id": idx,
|
| 120 |
+
"prompt": prompt_question,
|
| 121 |
+
"pred_response": outputs,
|
| 122 |
+
"gt_response": gt,
|
| 123 |
+
"model_id": model_name,
|
| 124 |
+
"question_type": question_type,
|
| 125 |
+
}) + "\n")
|
| 126 |
+
ans_file.flush()
|
| 127 |
+
|
| 128 |
+
ans_file.close()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
parser = argparse.ArgumentParser()
|
| 133 |
+
parser.add_argument("--model-path", type=str, default="checkpoints/llava3d-v1.5-7b-task-v3-tuning")
|
| 134 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 135 |
+
parser.add_argument("--video-folder", type=str, default="playground/data/LLaVA-3D-Pretrain")
|
| 136 |
+
parser.add_argument("--extra-prompt", type=str, default="The video captures 3D spatial information of a scene. Please focus on the spatial relationships in the video and answer the following questions.\n")
|
| 137 |
+
parser.add_argument("--question-file", type=str, default="playground/data/annotations/llava3d_sqa3d_val_question.json")
|
| 138 |
+
parser.add_argument("--answer-file", type=str, default="./llava3d_sqa3d_val_answer_pred.json")
|
| 139 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
| 140 |
+
parser.add_argument("--max-frame-num", type=int, default=32)
|
| 141 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 142 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
| 143 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
| 144 |
+
parser.add_argument("--temperature", type=float, default=0.)
|
| 145 |
+
parser.add_argument("--top_p", type=float, default=None)
|
| 146 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
| 147 |
+
parser.add_argument("--force_sample", type=bool, default=True)
|
| 148 |
+
args = parser.parse_args()
|
| 149 |
+
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import ray
|
| 6 |
+
import time
|
| 7 |
+
import numpy as np
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import shortuuid
|
| 10 |
+
import fasteners
|
| 11 |
+
|
| 12 |
+
# Fix bitsandbytes CUDA setup issue in Ray workers
|
| 13 |
+
os.environ['BNB_CUDA_VERSION'] = '121' # CUDA 12.1
|
| 14 |
+
os.environ['BITSANDBYTES_NOWELCOME'] = '1'
|
| 15 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = os.environ.get('CUDA_VISIBLE_DEVICES', '0,1,2,3')
|
| 16 |
+
|
| 17 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 18 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
| 19 |
+
from llava.model.builder import load_pretrained_model
|
| 20 |
+
from llava.utils import disable_torch_init
|
| 21 |
+
from llava.mm_utils import tokenizer_image_token, get_model_name_from_path
|
| 22 |
+
|
| 23 |
+
from PIL import Image
|
| 24 |
+
import math
|
| 25 |
+
from llava.eval.model_vqa import preprocess_qwen
|
| 26 |
+
|
| 27 |
+
from decord import VideoReader, cpu
|
| 28 |
+
import warnings
|
| 29 |
+
warnings.filterwarnings("ignore")
|
| 30 |
+
import copy
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_video(video_path, max_frames_num, fps=1, force_sample=False):
|
| 34 |
+
"""Load video frames from file."""
|
| 35 |
+
if max_frames_num == 0:
|
| 36 |
+
return np.zeros((1, 336, 336, 3))
|
| 37 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
| 38 |
+
total_frame_num = len(vr)
|
| 39 |
+
video_time = total_frame_num / vr.get_avg_fps()
|
| 40 |
+
fps = round(vr.get_avg_fps()/fps)
|
| 41 |
+
frame_idx = [i for i in range(0, len(vr), fps)]
|
| 42 |
+
frame_time = [i/fps for i in frame_idx]
|
| 43 |
+
if len(frame_idx) > max_frames_num or force_sample:
|
| 44 |
+
sample_fps = max_frames_num
|
| 45 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
|
| 46 |
+
frame_idx = uniform_sampled_frames.tolist()
|
| 47 |
+
frame_time = [i/vr.get_avg_fps() for i in frame_idx]
|
| 48 |
+
frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
|
| 49 |
+
spare_frames = vr.get_batch(frame_idx).asnumpy()
|
| 50 |
+
return spare_frames, frame_time, video_time
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@ray.remote(num_gpus=1)
|
| 54 |
+
def eval_model(questions, args):
|
| 55 |
+
# Fix bitsandbytes CUDA setup in worker process
|
| 56 |
+
gpu_ids = ray.get_gpu_ids()
|
| 57 |
+
if gpu_ids:
|
| 58 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_ids[0])
|
| 59 |
+
os.environ['BNB_CUDA_VERSION'] = '121' # CUDA 12.1
|
| 60 |
+
os.environ['BITSANDBYTES_NOWELCOME'] = '1'
|
| 61 |
+
|
| 62 |
+
# Model
|
| 63 |
+
disable_torch_init()
|
| 64 |
+
model_path = os.path.expanduser(args.model_path)
|
| 65 |
+
model_name = "llava_qwen_lora"
|
| 66 |
+
tokenizer, model, processor, context_len = load_pretrained_model(
|
| 67 |
+
model_path, args.model_base, model_name, torch_dtype="bfloat16"
|
| 68 |
+
)
|
| 69 |
+
model.to(device="cuda")
|
| 70 |
+
|
| 71 |
+
answer_file = os.path.expanduser(args.answer_file)
|
| 72 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
| 73 |
+
ans_file = open(answer_file, "a")
|
| 74 |
+
file_lock = fasteners.InterProcessLock(ans_file)
|
| 75 |
+
|
| 76 |
+
inference_time = []
|
| 77 |
+
feature_load_time = []
|
| 78 |
+
|
| 79 |
+
for line in tqdm(questions):
|
| 80 |
+
idx = line["id"]
|
| 81 |
+
question_type = line["metadata"]["question_type"]
|
| 82 |
+
dataset_name = line["metadata"]["dataset"]
|
| 83 |
+
video_id = line["video"].split("/")[-1]
|
| 84 |
+
|
| 85 |
+
# Get video path - assuming video files are in video_folder with .mp4 extension
|
| 86 |
+
video_path = os.path.join(args.video_folder, f"{video_id}.mp4")
|
| 87 |
+
|
| 88 |
+
gt = line["conversations"][1]["value"]
|
| 89 |
+
qs = line["conversations"][0]["value"].replace("<image>", "")
|
| 90 |
+
|
| 91 |
+
args.conv_mode = "qwen_1_5"
|
| 92 |
+
|
| 93 |
+
start_time = time.time()
|
| 94 |
+
|
| 95 |
+
# Try to load precomputed spatial features first
|
| 96 |
+
spatial_features = None
|
| 97 |
+
if args.feature_dir:
|
| 98 |
+
# Following the pattern from train.py: replace .mp4 with .pt and videos with spatial_features
|
| 99 |
+
feature_path = os.path.join(args.feature_dir, f"{video_id}.pt")
|
| 100 |
+
if not os.path.exists(feature_path):
|
| 101 |
+
# Try alternative path pattern
|
| 102 |
+
feature_path = video_path.replace('.mp4', '.pt').replace('videos', 'spatial_features')
|
| 103 |
+
|
| 104 |
+
if os.path.exists(feature_path):
|
| 105 |
+
# Load precomputed spatial features
|
| 106 |
+
feature_load_time.append(time.time() - start_time)
|
| 107 |
+
spatial_features = torch.load(feature_path, map_location='cuda')
|
| 108 |
+
if isinstance(spatial_features, dict) and 'spatial_features' in spatial_features:
|
| 109 |
+
spatial_features = spatial_features['spatial_features']
|
| 110 |
+
spatial_features = [spatial_features]
|
| 111 |
+
|
| 112 |
+
# Still need to load video for metadata, but can skip processing
|
| 113 |
+
video, frame_time, video_time = load_video(video_path, args.max_frame_num, 1, force_sample=True)
|
| 114 |
+
video = processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
|
| 115 |
+
video = [video]
|
| 116 |
+
else:
|
| 117 |
+
# No precomputed features, process normally
|
| 118 |
+
video, frame_time, video_time = load_video(video_path, args.max_frame_num, 1, force_sample=True)
|
| 119 |
+
video = processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
|
| 120 |
+
video = [video]
|
| 121 |
+
else:
|
| 122 |
+
# No feature directory specified, process normally
|
| 123 |
+
video, frame_time, video_time = load_video(video_path, args.max_frame_num, 1, force_sample=True)
|
| 124 |
+
video = processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
|
| 125 |
+
video = [video]
|
| 126 |
+
|
| 127 |
+
time_instruction = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
|
| 128 |
+
question = DEFAULT_IMAGE_TOKEN + f"{time_instruction}\n{qs}"
|
| 129 |
+
|
| 130 |
+
if args.extra_prompt:
|
| 131 |
+
question = DEFAULT_IMAGE_TOKEN + f"{args.extra_prompt}\n{time_instruction}\n{qs}"
|
| 132 |
+
|
| 133 |
+
conv = copy.deepcopy(conv_templates[args.conv_mode])
|
| 134 |
+
conv.append_message(conv.roles[0], question)
|
| 135 |
+
conv.append_message(conv.roles[1], None)
|
| 136 |
+
prompt_question = conv.get_prompt()
|
| 137 |
+
|
| 138 |
+
input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to("cuda")
|
| 139 |
+
|
| 140 |
+
with torch.inference_mode():
|
| 141 |
+
output_ids = model.generate(
|
| 142 |
+
input_ids,
|
| 143 |
+
images=video,
|
| 144 |
+
spatial_features=spatial_features, # Pass precomputed spatial features
|
| 145 |
+
modalities=["video"],
|
| 146 |
+
do_sample=True if args.temperature > 0 else False,
|
| 147 |
+
temperature=args.temperature,
|
| 148 |
+
top_p=args.top_p,
|
| 149 |
+
num_beams=args.num_beams,
|
| 150 |
+
max_new_tokens=512,
|
| 151 |
+
use_cache=True,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
inference_time.append(time.time() - start_time)
|
| 155 |
+
|
| 156 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 157 |
+
|
| 158 |
+
ans_id = shortuuid.uuid()
|
| 159 |
+
|
| 160 |
+
with file_lock:
|
| 161 |
+
ans_file.write(json.dumps({
|
| 162 |
+
"dataset": dataset_name,
|
| 163 |
+
"sample_id": idx,
|
| 164 |
+
"prompt": prompt_question,
|
| 165 |
+
"pred_response": outputs,
|
| 166 |
+
"gt_response": gt,
|
| 167 |
+
"model_id": model_name,
|
| 168 |
+
"question_type": question_type,
|
| 169 |
+
}) + "\n")
|
| 170 |
+
ans_file.flush()
|
| 171 |
+
|
| 172 |
+
ans_file.close()
|
| 173 |
+
|
| 174 |
+
return {
|
| 175 |
+
'inference_time': inference_time,
|
| 176 |
+
'feature_load_time': feature_load_time
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
parser = argparse.ArgumentParser()
|
| 182 |
+
parser.add_argument("--model-path", type=str, default="checkpoints/llava3d-v1.5-7b-task-v3-tuning")
|
| 183 |
+
parser.add_argument("--model-base", type=str, default=None)
|
| 184 |
+
parser.add_argument("--video-folder", type=str, default="playground/data/LLaVA-3D-Pretrain")
|
| 185 |
+
parser.add_argument("--feature-dir", type=str, default=None,
|
| 186 |
+
help="Directory containing precomputed spatial features")
|
| 187 |
+
parser.add_argument("--extra-prompt", type=str, default="The video captures 3D spatial information of a scene. Please focus on the spatial relationships in the video and answer the following questions.")
|
| 188 |
+
parser.add_argument("--question-file", type=str, default="playground/data/annotations/llava3d_sqa3d_val_question.json")
|
| 189 |
+
parser.add_argument("--answer-file", type=str, default="./llava3d_sqa3d_val_answer_pred.jsonl")
|
| 190 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
| 191 |
+
parser.add_argument("--max-frame-num", type=int, default=32)
|
| 192 |
+
parser.add_argument("--n_gpu", type=int, default=4)
|
| 193 |
+
parser.add_argument("--temperature", type=float, default=0.)
|
| 194 |
+
parser.add_argument("--top_p", type=float, default=None)
|
| 195 |
+
parser.add_argument("--num_beams", type=int, default=1)
|
| 196 |
+
parser.add_argument("--force_sample", type=bool, default=True)
|
| 197 |
+
parser.add_argument("--debug", action="store_true",
|
| 198 |
+
help="Enable debug mode with Ray local mode")
|
| 199 |
+
args = parser.parse_args()
|
| 200 |
+
|
| 201 |
+
# Load questions
|
| 202 |
+
with open(args.question_file, 'r') as file:
|
| 203 |
+
questions = json.load(file)
|
| 204 |
+
|
| 205 |
+
if os.path.exists(args.answer_file):
|
| 206 |
+
print(f"The {args.answer_file} already exists! Appending to it.")
|
| 207 |
+
|
| 208 |
+
# Initialize Ray
|
| 209 |
+
if args.n_gpu == 1 and args.debug:
|
| 210 |
+
# Use Ray local mode for debugging
|
| 211 |
+
ray.init(local_mode=True)
|
| 212 |
+
else:
|
| 213 |
+
ray.init(num_gpus=args.n_gpu)
|
| 214 |
+
|
| 215 |
+
# Distribute questions across GPUs
|
| 216 |
+
features = []
|
| 217 |
+
for i in range(args.n_gpu):
|
| 218 |
+
features.append(eval_model.remote(questions[i::args.n_gpu], args))
|
| 219 |
+
|
| 220 |
+
# Get results
|
| 221 |
+
results = ray.get(features)
|
| 222 |
+
|
| 223 |
+
# Aggregate statistics
|
| 224 |
+
all_inference_times = []
|
| 225 |
+
all_feature_load_times = []
|
| 226 |
+
|
| 227 |
+
for result in results:
|
| 228 |
+
all_inference_times.extend(result['inference_time'])
|
| 229 |
+
all_feature_load_times.extend(result['feature_load_time'])
|
| 230 |
+
|
| 231 |
+
print(f"Average inference time: {np.mean(all_inference_times):.2f} seconds")
|
| 232 |
+
if all_feature_load_times:
|
| 233 |
+
print(f"Average feature load time: {np.mean(all_feature_load_times):.4f} seconds")
|
| 234 |
+
print(f"Total questions processed: {len(questions)}")
|
spatial-model/VLM-3R/llava/eval/scanqa_evaluator.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import json
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import mmengine
|
| 5 |
+
from pycocoevalcap.bleu.bleu import Bleu
|
| 6 |
+
from pycocoevalcap.meteor.meteor import Meteor
|
| 7 |
+
from pycocoevalcap.rouge.rouge import Rouge
|
| 8 |
+
from pycocoevalcap.cider.cider import Cider
|
| 9 |
+
from pycocoevalcap.spice.spice import Spice
|
| 10 |
+
from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer
|
| 11 |
+
|
| 12 |
+
tokenizer = PTBTokenizer()
|
| 13 |
+
scorers = [
|
| 14 |
+
(Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]),
|
| 15 |
+
(Meteor(), "METEOR"),
|
| 16 |
+
(Rouge(), "ROUGE_L"),
|
| 17 |
+
(Cider(), "CIDEr"),
|
| 18 |
+
(Spice(), "SPICE")
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# refer to LEO: embodied-generalist
|
| 23 |
+
# https://github.com/embodied-generalist/embodied-generalist/blob/477dc44b8b18dbfbe6823c307436d896ec8b062e/data/data_utils.py#L322-L379
|
| 24 |
+
def clean_answer(data):
|
| 25 |
+
data = data.lower()
|
| 26 |
+
data = re.sub('[ ]+$' ,'', data)
|
| 27 |
+
data = re.sub('^[ ]+' ,'', data)
|
| 28 |
+
data = re.sub(' {2,}', ' ', data)
|
| 29 |
+
|
| 30 |
+
data = re.sub('\.[ ]{2,}', '. ', data)
|
| 31 |
+
data = re.sub('[^a-zA-Z0-9,\'\s\-:]+', '', data)
|
| 32 |
+
data = re.sub('ç' ,'c', data)
|
| 33 |
+
data = re.sub('’' ,'\'', data)
|
| 34 |
+
data = re.sub(r'\bletf\b' ,'left', data)
|
| 35 |
+
data = re.sub(r'\blet\b' ,'left', data)
|
| 36 |
+
data = re.sub(r'\btehre\b' ,'there', data)
|
| 37 |
+
data = re.sub(r'\brigth\b' ,'right', data)
|
| 38 |
+
data = re.sub(r'\brght\b' ,'right', data)
|
| 39 |
+
data = re.sub(r'\bbehine\b', 'behind', data)
|
| 40 |
+
data = re.sub(r'\btv\b' ,'TV', data)
|
| 41 |
+
data = re.sub(r'\bchai\b' ,'chair', data)
|
| 42 |
+
data = re.sub(r'\bwasing\b' ,'washing', data)
|
| 43 |
+
data = re.sub(r'\bwaslked\b' ,'walked', data)
|
| 44 |
+
data = re.sub(r'\boclock\b' ,'o\'clock', data)
|
| 45 |
+
data = re.sub(r'\bo\'[ ]+clock\b' ,'o\'clock', data)
|
| 46 |
+
|
| 47 |
+
# digit to word, only for answer
|
| 48 |
+
data = re.sub(r'\b0\b', 'zero', data)
|
| 49 |
+
data = re.sub(r'\bnone\b', 'zero', data)
|
| 50 |
+
data = re.sub(r'\b1\b', 'one', data)
|
| 51 |
+
data = re.sub(r'\b2\b', 'two', data)
|
| 52 |
+
data = re.sub(r'\b3\b', 'three', data)
|
| 53 |
+
data = re.sub(r'\b4\b', 'four', data)
|
| 54 |
+
data = re.sub(r'\b5\b', 'five', data)
|
| 55 |
+
data = re.sub(r'\b6\b', 'six', data)
|
| 56 |
+
data = re.sub(r'\b7\b', 'seven', data)
|
| 57 |
+
data = re.sub(r'\b8\b', 'eight', data)
|
| 58 |
+
data = re.sub(r'\b9\b', 'nine', data)
|
| 59 |
+
data = re.sub(r'\b10\b', 'ten', data)
|
| 60 |
+
data = re.sub(r'\b11\b', 'eleven', data)
|
| 61 |
+
data = re.sub(r'\b12\b', 'twelve', data)
|
| 62 |
+
data = re.sub(r'\b13\b', 'thirteen', data)
|
| 63 |
+
data = re.sub(r'\b14\b', 'fourteen', data)
|
| 64 |
+
data = re.sub(r'\b15\b', 'fifteen', data)
|
| 65 |
+
data = re.sub(r'\b16\b', 'sixteen', data)
|
| 66 |
+
data = re.sub(r'\b17\b', 'seventeen', data)
|
| 67 |
+
data = re.sub(r'\b18\b', 'eighteen', data)
|
| 68 |
+
data = re.sub(r'\b19\b', 'nineteen', data)
|
| 69 |
+
data = re.sub(r'\b20\b', 'twenty', data)
|
| 70 |
+
data = re.sub(r'\b23\b', 'twenty-three', data)
|
| 71 |
+
|
| 72 |
+
# misc
|
| 73 |
+
# no1, mat2, etc
|
| 74 |
+
data = re.sub(r'\b([a-zA-Z]+)([0-9])\b' ,r'\g<1>', data)
|
| 75 |
+
data = re.sub(r'\ba\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 76 |
+
data = re.sub(r'\ban\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 77 |
+
data = re.sub(r'\bthe\b ([a-zA-Z]+)' ,r'\g<1>', data)
|
| 78 |
+
|
| 79 |
+
data = re.sub(r'\bbackwards\b', 'backward', data)
|
| 80 |
+
|
| 81 |
+
return data
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# refer to LEO: embodied-generalist
|
| 85 |
+
# https://github.com/embodied-generalist/embodied-generalist/blob/477dc44b8b18dbfbe6823c307436d896ec8b062e/evaluator/scanqa_eval.py#L41-L50
|
| 86 |
+
def classify_question_type(question):
|
| 87 |
+
question_lower = question.lower()
|
| 88 |
+
|
| 89 |
+
# Color questions
|
| 90 |
+
if question_lower.startswith('what color') or question_lower.startswith('what is the color'):
|
| 91 |
+
return 'Color'
|
| 92 |
+
|
| 93 |
+
# Object nature questions
|
| 94 |
+
if (question_lower.startswith('what type') or
|
| 95 |
+
question_lower.startswith('what shape') or
|
| 96 |
+
question_lower.startswith('what kind')):
|
| 97 |
+
return 'Object nature'
|
| 98 |
+
|
| 99 |
+
# Place questions
|
| 100 |
+
if question_lower.startswith('where is'):
|
| 101 |
+
return 'Place'
|
| 102 |
+
|
| 103 |
+
# Number questions
|
| 104 |
+
if question_lower.startswith('how many'):
|
| 105 |
+
return 'Number'
|
| 106 |
+
|
| 107 |
+
# Object questions (What is, except color questions)
|
| 108 |
+
if question_lower.startswith('what is') and not question_lower.startswith('what is the color'):
|
| 109 |
+
return 'Object'
|
| 110 |
+
|
| 111 |
+
# Everything else is Other
|
| 112 |
+
return 'Other'
|
| 113 |
+
|
| 114 |
+
def answer_match(pred, gts):
|
| 115 |
+
# return EM and refined EM
|
| 116 |
+
if pred in gts:
|
| 117 |
+
return 1, 1
|
| 118 |
+
for gt in gts:
|
| 119 |
+
if ''.join(pred.split()) in ''.join(gt.split()) or ''.join(gt.split()) in ''.join(pred.split()):
|
| 120 |
+
return 0, 1
|
| 121 |
+
return 0, 0
|
| 122 |
+
|
| 123 |
+
def calc_scanqa_score(preds, gts, tokenizer, scorers):
|
| 124 |
+
val_scores = {}
|
| 125 |
+
tmp_preds = {}
|
| 126 |
+
tmp_targets = {}
|
| 127 |
+
acc, refined_acc = 0, 0
|
| 128 |
+
|
| 129 |
+
# Initialize subtask tracking
|
| 130 |
+
subtasks = ['Object', 'Color', 'Object nature', 'Place', 'Number', 'Other']
|
| 131 |
+
subtask_stats = {task: {
|
| 132 |
+
'count': 0,
|
| 133 |
+
'acc': 0,
|
| 134 |
+
'refined_acc': 0,
|
| 135 |
+
'tmp_preds': {},
|
| 136 |
+
'tmp_targets': {}
|
| 137 |
+
} for task in subtasks}
|
| 138 |
+
|
| 139 |
+
print("Total samples:", len(preds))
|
| 140 |
+
|
| 141 |
+
# Create a dictionary to map question_id to ground truth data
|
| 142 |
+
gt_dict = {gt['question_id']: gt for gt in gts}
|
| 143 |
+
|
| 144 |
+
# Check if all predictions have corresponding ground truth
|
| 145 |
+
missing_gt = [pred['question_id'] for pred in preds if pred['question_id'] not in gt_dict]
|
| 146 |
+
if missing_gt:
|
| 147 |
+
print(f"Warning: {len(missing_gt)} predictions have no corresponding ground truth")
|
| 148 |
+
print(f"Missing question_ids: {missing_gt[:10]}...") # Show first 10
|
| 149 |
+
|
| 150 |
+
matched_count = 0
|
| 151 |
+
for item_id, pred in tqdm(enumerate(preds)):
|
| 152 |
+
question_id = pred['question_id']
|
| 153 |
+
|
| 154 |
+
# Skip if no ground truth found
|
| 155 |
+
if question_id not in gt_dict:
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
gt = gt_dict[question_id]
|
| 159 |
+
matched_count += 1
|
| 160 |
+
|
| 161 |
+
# Classify question type
|
| 162 |
+
question_type = classify_question_type(gt['question'])
|
| 163 |
+
|
| 164 |
+
pred_answer = pred['text']
|
| 165 |
+
gt_answers = gt['answers']
|
| 166 |
+
pred_answer = clean_answer(pred_answer)
|
| 167 |
+
ref_captions = [clean_answer(gt_answer) for gt_answer in gt_answers]
|
| 168 |
+
tmp_acc, tmp_refined_acc = answer_match(pred_answer, ref_captions)
|
| 169 |
+
|
| 170 |
+
# Update overall metrics
|
| 171 |
+
acc += tmp_acc
|
| 172 |
+
refined_acc += tmp_refined_acc
|
| 173 |
+
tmp_preds[item_id] = [{'caption': pred_answer}]
|
| 174 |
+
ref_captions = [p.replace("\n", " ").strip() for p in ref_captions]
|
| 175 |
+
tmp_targets[item_id] = [{'caption': caption} for caption in ref_captions]
|
| 176 |
+
|
| 177 |
+
# Update subtask metrics
|
| 178 |
+
subtask_stats[question_type]['count'] += 1
|
| 179 |
+
subtask_stats[question_type]['acc'] += tmp_acc
|
| 180 |
+
subtask_stats[question_type]['refined_acc'] += tmp_refined_acc
|
| 181 |
+
subtask_stats[question_type]['tmp_preds'][item_id] = [{'caption': pred_answer}]
|
| 182 |
+
subtask_stats[question_type]['tmp_targets'][item_id] = [{'caption': caption} for caption in ref_captions]
|
| 183 |
+
|
| 184 |
+
print(f"Matched {matched_count} predictions with ground truth")
|
| 185 |
+
|
| 186 |
+
if matched_count == 0:
|
| 187 |
+
print("Error: No matched predictions found!")
|
| 188 |
+
return val_scores, subtask_stats
|
| 189 |
+
|
| 190 |
+
# Calculate overall scores
|
| 191 |
+
tmp_preds = tokenizer.tokenize(tmp_preds)
|
| 192 |
+
tmp_targets = tokenizer.tokenize(tmp_targets)
|
| 193 |
+
acc = acc / matched_count
|
| 194 |
+
refined_acc = refined_acc / matched_count
|
| 195 |
+
val_scores["[scanqa] EM1"] = acc
|
| 196 |
+
val_scores["[scanqa] EM1_refined"] = refined_acc
|
| 197 |
+
for scorer, method in scorers:
|
| 198 |
+
score, scores = scorer.compute_score(tmp_targets, tmp_preds)
|
| 199 |
+
if type(method) == list:
|
| 200 |
+
for sc, scs, m in zip(score, scores, method):
|
| 201 |
+
val_scores[f"[scanqa] {m}"] = sc
|
| 202 |
+
else:
|
| 203 |
+
val_scores[f"[scanqa] {method}"] = score
|
| 204 |
+
|
| 205 |
+
# Calculate subtask scores
|
| 206 |
+
for task in subtasks:
|
| 207 |
+
if subtask_stats[task]['count'] > 0:
|
| 208 |
+
# Calculate EM scores
|
| 209 |
+
subtask_stats[task]['em1'] = subtask_stats[task]['acc'] / subtask_stats[task]['count']
|
| 210 |
+
subtask_stats[task]['em1_refined'] = subtask_stats[task]['refined_acc'] / subtask_stats[task]['count']
|
| 211 |
+
|
| 212 |
+
# Calculate other metrics if there are samples
|
| 213 |
+
if subtask_stats[task]['tmp_preds']:
|
| 214 |
+
task_preds = tokenizer.tokenize(subtask_stats[task]['tmp_preds'])
|
| 215 |
+
task_targets = tokenizer.tokenize(subtask_stats[task]['tmp_targets'])
|
| 216 |
+
|
| 217 |
+
for scorer, method in scorers:
|
| 218 |
+
score, scores = scorer.compute_score(task_targets, task_preds)
|
| 219 |
+
if type(method) == list:
|
| 220 |
+
for sc, scs, m in zip(score, scores, method):
|
| 221 |
+
subtask_stats[task][m.lower()] = sc
|
| 222 |
+
else:
|
| 223 |
+
subtask_stats[task][method.lower()] = score
|
| 224 |
+
|
| 225 |
+
return val_scores, subtask_stats
|
| 226 |
+
|
| 227 |
+
def print_subtask_results_table(subtask_stats):
|
| 228 |
+
print("\n" + "="*80)
|
| 229 |
+
print("SUBTASK EVALUATION RESULTS")
|
| 230 |
+
print("="*80)
|
| 231 |
+
|
| 232 |
+
# Print header with only the 5 requested metrics
|
| 233 |
+
header = f"{'Question type':<15} {'Count':<8} {'BLEU-1':<8} {'BLEU-4':<8} {'METEOR':<8} {'ROUGE-L':<8} {'CIDEr':<8}"
|
| 234 |
+
print(header)
|
| 235 |
+
print("-" * 80)
|
| 236 |
+
|
| 237 |
+
# Print results for each subtask
|
| 238 |
+
for task in ['Object', 'Color', 'Object nature', 'Place', 'Number', 'Other']:
|
| 239 |
+
if subtask_stats[task]['count'] > 0:
|
| 240 |
+
bleu_1 = subtask_stats[task].get('bleu_1', 0) * 100 if 'bleu_1' in subtask_stats[task] else 0
|
| 241 |
+
bleu_4 = subtask_stats[task].get('bleu_4', 0) * 100 if 'bleu_4' in subtask_stats[task] else 0
|
| 242 |
+
meteor = subtask_stats[task].get('meteor', 0) * 100 if 'meteor' in subtask_stats[task] else 0
|
| 243 |
+
rouge_l = subtask_stats[task].get('rouge_l', 0) * 100 if 'rouge_l' in subtask_stats[task] else 0
|
| 244 |
+
cider = subtask_stats[task].get('cider', 0) * 100 if 'cider' in subtask_stats[task] else 0
|
| 245 |
+
|
| 246 |
+
row = f"{task:<15} {subtask_stats[task]['count']:<8} {bleu_1:<8.2f} {bleu_4:<8.2f} {meteor:<8.2f} {rouge_l:<8.2f} {cider:<8.2f}"
|
| 247 |
+
print(row)
|
| 248 |
+
else:
|
| 249 |
+
row = f"{task:<15} {subtask_stats[task]['count']:<8} {'N/A':<8} {'N/A':<8} {'N/A':<8} {'N/A':<8} {'N/A':<8}"
|
| 250 |
+
print(row)
|
| 251 |
+
|
| 252 |
+
print("-" * 80)
|
| 253 |
+
|
| 254 |
+
# Calculate and print totals
|
| 255 |
+
total_count = sum(subtask_stats[task]['count'] for task in subtask_stats)
|
| 256 |
+
if total_count > 0:
|
| 257 |
+
# Calculate weighted averages for the 5 requested metrics
|
| 258 |
+
total_bleu_1 = sum(subtask_stats[task].get('bleu_1', 0) * subtask_stats[task]['count']
|
| 259 |
+
for task in subtask_stats if subtask_stats[task]['count'] > 0) / total_count * 100
|
| 260 |
+
total_bleu_4 = sum(subtask_stats[task].get('bleu_4', 0) * subtask_stats[task]['count']
|
| 261 |
+
for task in subtask_stats if subtask_stats[task]['count'] > 0) / total_count * 100
|
| 262 |
+
total_meteor = sum(subtask_stats[task].get('meteor', 0) * subtask_stats[task]['count']
|
| 263 |
+
for task in subtask_stats if subtask_stats[task]['count'] > 0) / total_count * 100
|
| 264 |
+
total_rouge_l = sum(subtask_stats[task].get('rouge_l', 0) * subtask_stats[task]['count']
|
| 265 |
+
for task in subtask_stats if subtask_stats[task]['count'] > 0) / total_count * 100
|
| 266 |
+
total_cider = sum(subtask_stats[task].get('cider', 0) * subtask_stats[task]['count']
|
| 267 |
+
for task in subtask_stats if subtask_stats[task]['count'] > 0) / total_count * 100
|
| 268 |
+
|
| 269 |
+
total_row = f"{'TOTAL':<15} {total_count:<8} {total_bleu_1:<8.2f} {total_bleu_4:<8.2f} {total_meteor:<8.2f} {total_rouge_l:<8.2f} {total_cider:<8.2f}"
|
| 270 |
+
print(total_row)
|
| 271 |
+
|
| 272 |
+
print("="*80)
|
| 273 |
+
|
| 274 |
+
pred_json = 'results/llava_next_video_val_answer_pred_vsibench.json'
|
| 275 |
+
preds = [json.loads(q) for q in open(pred_json, "r")]
|
| 276 |
+
gt_json = 'thinking-in-space/data/scanqa/ScanQA_v1.0_val.json'
|
| 277 |
+
gts = mmengine.load(gt_json)
|
| 278 |
+
|
| 279 |
+
val_scores, subtask_stats = calc_scanqa_score(preds, gts, tokenizer, scorers)
|
| 280 |
+
print("\nOverall Scores:")
|
| 281 |
+
print(val_scores)
|
| 282 |
+
|
| 283 |
+
print_subtask_results_table(subtask_stats)
|
spatial-model/VLM-3R/llava/mm_utils.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
import base64
|
| 4 |
+
import math
|
| 5 |
+
import ast
|
| 6 |
+
import re
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import StoppingCriteria
|
| 9 |
+
from llava.constants import IMAGE_TOKEN_INDEX
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def resize_and_center_crop(image, shortest_edge_length):
|
| 13 |
+
# Calculate new dimensions and resize
|
| 14 |
+
aspect_ratio = float(image.width) / float(image.height)
|
| 15 |
+
if aspect_ratio > 1:
|
| 16 |
+
new_width = int(shortest_edge_length * aspect_ratio)
|
| 17 |
+
new_height = shortest_edge_length
|
| 18 |
+
else:
|
| 19 |
+
new_width = shortest_edge_length
|
| 20 |
+
new_height = int(shortest_edge_length / aspect_ratio)
|
| 21 |
+
resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
|
| 22 |
+
|
| 23 |
+
# Calculate the position and perform the center crop
|
| 24 |
+
left = (new_width - shortest_edge_length) / 2
|
| 25 |
+
top = (new_height - shortest_edge_length) / 2
|
| 26 |
+
right = (new_width + shortest_edge_length) / 2
|
| 27 |
+
bottom = (new_height + shortest_edge_length) / 2
|
| 28 |
+
cropped_image = resized_image.crop((left, top, right, bottom))
|
| 29 |
+
|
| 30 |
+
return cropped_image
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def auto_pad_images(image, grid_params):
|
| 34 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
| 35 |
+
assert len(grid_params) > 0, "Grid parameters should not be empty"
|
| 36 |
+
|
| 37 |
+
# Step 1: Calculate and find the closest aspect ratio
|
| 38 |
+
input_width, input_height = image.size
|
| 39 |
+
input_aspect_ratio = input_width / input_height
|
| 40 |
+
candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
|
| 41 |
+
closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
|
| 42 |
+
|
| 43 |
+
candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
|
| 44 |
+
|
| 45 |
+
target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
|
| 46 |
+
|
| 47 |
+
resize_width, resize_height = target_resolution
|
| 48 |
+
if input_width > input_height:
|
| 49 |
+
resize_height = int(resize_width / input_aspect_ratio)
|
| 50 |
+
else:
|
| 51 |
+
resize_width = int(resize_height * input_aspect_ratio)
|
| 52 |
+
resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
|
| 53 |
+
|
| 54 |
+
# Step 5: Pad the resized image if necessary to match the target resolution
|
| 55 |
+
pad_width = target_resolution[0] - resize_width
|
| 56 |
+
pad_height = target_resolution[1] - resize_height
|
| 57 |
+
padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
|
| 58 |
+
padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
|
| 59 |
+
|
| 60 |
+
return padded_image
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def extract_patches(image, patch_size, overlap_ratio):
|
| 64 |
+
assert isinstance(image, Image.Image), "Input should be a Pillow Image"
|
| 65 |
+
assert patch_size > 0, "Patch size should be greater than 0"
|
| 66 |
+
assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
|
| 67 |
+
|
| 68 |
+
W, H = image.size
|
| 69 |
+
patches = []
|
| 70 |
+
|
| 71 |
+
stride = int(patch_size * (1 - overlap_ratio))
|
| 72 |
+
|
| 73 |
+
num_patches_y = (H - patch_size) // stride + 1
|
| 74 |
+
num_patches_x = (W - patch_size) // stride + 1
|
| 75 |
+
|
| 76 |
+
y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
|
| 77 |
+
x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
|
| 78 |
+
|
| 79 |
+
for y in range(y_start, y_start + num_patches_y * stride, stride):
|
| 80 |
+
for x in range(x_start, x_start + num_patches_x * stride, stride):
|
| 81 |
+
patch = image.crop((x, y, x + patch_size, y + patch_size))
|
| 82 |
+
patches.append(patch)
|
| 83 |
+
|
| 84 |
+
return patches
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def process_highres_image_crop_split(image, data_args, processor=None):
|
| 88 |
+
crop_resolution = data_args.image_crop_resolution
|
| 89 |
+
split_resolution = data_args.image_split_resolution
|
| 90 |
+
if processor is None:
|
| 91 |
+
processor = data_args.image_processor
|
| 92 |
+
image_crop = resize_and_center_crop(image, crop_resolution)
|
| 93 |
+
image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
|
| 94 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
| 95 |
+
return torch.stack(image_patches, dim=0)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def process_highres_image(image, processor, grid_pinpoints):
|
| 99 |
+
grid_params = [int(x) for x in grid_pinpoints.split(",")]
|
| 100 |
+
width_height = max(image.size)
|
| 101 |
+
fit_grid_params = [x for x in grid_params if x >= width_height]
|
| 102 |
+
if len(fit_grid_params) == 0:
|
| 103 |
+
select_size = max(grid_params)
|
| 104 |
+
else:
|
| 105 |
+
select_size = min(fit_grid_params)
|
| 106 |
+
# FIXME: always select the 448
|
| 107 |
+
select_size = max(grid_params)
|
| 108 |
+
image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
|
| 109 |
+
|
| 110 |
+
# FIXME: this seems to be a bug that it always resizes instead of padding
|
| 111 |
+
image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
|
| 112 |
+
image_padded = image_padded.resize((select_size, select_size))
|
| 113 |
+
image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
|
| 114 |
+
image_patches = [image_original_resize] + image_patches
|
| 115 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
| 116 |
+
return torch.stack(image_patches, dim=0)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def select_best_resolution(original_size, possible_resolutions):
|
| 120 |
+
"""
|
| 121 |
+
Selects the best resolution from a list of possible resolutions based on the original size.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
original_size (tuple): The original size of the image in the format (width, height).
|
| 125 |
+
possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
tuple: The best fit resolution in the format (width, height).
|
| 129 |
+
"""
|
| 130 |
+
original_width, original_height = original_size
|
| 131 |
+
best_fit = None
|
| 132 |
+
max_effective_resolution = 0
|
| 133 |
+
min_wasted_resolution = float("inf")
|
| 134 |
+
|
| 135 |
+
for width, height in possible_resolutions:
|
| 136 |
+
# Calculate the downscaled size to keep the aspect ratio
|
| 137 |
+
scale = min(width / original_width, height / original_height)
|
| 138 |
+
downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
|
| 139 |
+
|
| 140 |
+
# Calculate effective and wasted resolutions
|
| 141 |
+
effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
|
| 142 |
+
wasted_resolution = (width * height) - effective_resolution
|
| 143 |
+
|
| 144 |
+
if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
|
| 145 |
+
max_effective_resolution = effective_resolution
|
| 146 |
+
min_wasted_resolution = wasted_resolution
|
| 147 |
+
best_fit = (width, height)
|
| 148 |
+
|
| 149 |
+
return best_fit
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def resize_and_pad_image(image, target_resolution):
|
| 153 |
+
"""
|
| 154 |
+
Resize and pad an image to a target resolution while maintaining aspect ratio.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
image (PIL.Image.Image): The input image.
|
| 158 |
+
target_resolution (tuple): The target resolution (width, height) of the image.
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
PIL.Image.Image: The resized and padded image.
|
| 162 |
+
"""
|
| 163 |
+
original_width, original_height = image.size
|
| 164 |
+
target_width, target_height = target_resolution
|
| 165 |
+
|
| 166 |
+
# Determine which dimension (width or height) to fill
|
| 167 |
+
scale_w = target_width / original_width
|
| 168 |
+
scale_h = target_height / original_height
|
| 169 |
+
|
| 170 |
+
if scale_w < scale_h:
|
| 171 |
+
# Width will be filled completely
|
| 172 |
+
new_width = target_width
|
| 173 |
+
new_height = min(math.ceil(original_height * scale_w), target_height)
|
| 174 |
+
else:
|
| 175 |
+
# Height will be filled completely
|
| 176 |
+
new_height = target_height
|
| 177 |
+
new_width = min(math.ceil(original_width * scale_h), target_width)
|
| 178 |
+
|
| 179 |
+
# Resize the image
|
| 180 |
+
resized_image = image.resize((new_width, new_height))
|
| 181 |
+
|
| 182 |
+
# Create a new image with the target size and paste the resized image onto it
|
| 183 |
+
new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
|
| 184 |
+
paste_x = (target_width - new_width) // 2
|
| 185 |
+
paste_y = (target_height - new_height) // 2
|
| 186 |
+
new_image.paste(resized_image, (paste_x, paste_y))
|
| 187 |
+
|
| 188 |
+
return new_image
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def divide_to_patches(image, patch_size):
|
| 192 |
+
"""
|
| 193 |
+
Divides an image into patches of a specified size.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
image (PIL.Image.Image): The input image.
|
| 197 |
+
patch_size (int): The size of each patch.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
list: A list of PIL.Image.Image objects representing the patches.
|
| 201 |
+
"""
|
| 202 |
+
patches = []
|
| 203 |
+
width, height = image.size
|
| 204 |
+
for i in range(0, height, patch_size):
|
| 205 |
+
for j in range(0, width, patch_size):
|
| 206 |
+
box = (j, i, j + patch_size, i + patch_size)
|
| 207 |
+
patch = image.crop(box)
|
| 208 |
+
patches.append(patch)
|
| 209 |
+
|
| 210 |
+
return patches
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
|
| 214 |
+
"""
|
| 215 |
+
Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
image_size (tuple): The size of the input image in the format (width, height).
|
| 219 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
| 220 |
+
patch_size (int): The size of each image patch.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
tuple: The shape of the image patch grid in the format (width, height).
|
| 224 |
+
"""
|
| 225 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
| 226 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
| 227 |
+
# Use regex to extract the range from the input string
|
| 228 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
| 229 |
+
range_start = tuple(map(int, matches[0]))
|
| 230 |
+
range_end = tuple(map(int, matches[-1]))
|
| 231 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
| 232 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
| 233 |
+
# Multiply all elements by patch_size
|
| 234 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
| 235 |
+
if type(grid_pinpoints) is list:
|
| 236 |
+
possible_resolutions = grid_pinpoints
|
| 237 |
+
else:
|
| 238 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
| 239 |
+
width, height = select_best_resolution(image_size, possible_resolutions)
|
| 240 |
+
return width // patch_size, height // patch_size
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def process_anyres_image(image, processor, grid_pinpoints):
|
| 244 |
+
"""
|
| 245 |
+
Process an image with variable resolutions.
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
image (PIL.Image.Image): The input image to be processed.
|
| 249 |
+
processor: The image processor object.
|
| 250 |
+
grid_pinpoints (str): A string representation of a list of possible resolutions.
|
| 251 |
+
|
| 252 |
+
Returns:
|
| 253 |
+
torch.Tensor: A tensor containing the processed image patches.
|
| 254 |
+
"""
|
| 255 |
+
# Convert grid_pinpoints from string to list
|
| 256 |
+
if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
|
| 257 |
+
try:
|
| 258 |
+
patch_size = processor.size[0]
|
| 259 |
+
except Exception as e:
|
| 260 |
+
patch_size = processor.size["shortest_edge"]
|
| 261 |
+
assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
|
| 262 |
+
# Use regex to extract the range from the input string
|
| 263 |
+
matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
|
| 264 |
+
range_start = tuple(map(int, matches[0]))
|
| 265 |
+
range_end = tuple(map(int, matches[-1]))
|
| 266 |
+
# Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
|
| 267 |
+
grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
|
| 268 |
+
# Multiply all elements by patch_size
|
| 269 |
+
grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
|
| 270 |
+
|
| 271 |
+
if type(grid_pinpoints) is list:
|
| 272 |
+
possible_resolutions = grid_pinpoints
|
| 273 |
+
else:
|
| 274 |
+
possible_resolutions = ast.literal_eval(grid_pinpoints)
|
| 275 |
+
best_resolution = select_best_resolution(image.size, possible_resolutions)
|
| 276 |
+
image_padded = resize_and_pad_image(image, best_resolution)
|
| 277 |
+
|
| 278 |
+
patches = divide_to_patches(image_padded, processor.crop_size["height"])
|
| 279 |
+
|
| 280 |
+
# FIXME: this seems to be a bug that it resizes instead of pad.
|
| 281 |
+
# but to keep it consistent with previous, i will keep it as it is
|
| 282 |
+
# TODO: uncomment below to ablate with the padding
|
| 283 |
+
if isinstance(processor.size, dict):
|
| 284 |
+
shortest_edge = processor.size["shortest_edge"]
|
| 285 |
+
else:
|
| 286 |
+
shortest_edge = min(processor.size)
|
| 287 |
+
image_original_resize = image.resize((shortest_edge, shortest_edge))
|
| 288 |
+
# image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
| 289 |
+
# image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
|
| 290 |
+
|
| 291 |
+
image_patches = [image_original_resize] + patches
|
| 292 |
+
image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
|
| 293 |
+
return torch.stack(image_patches, dim=0)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def load_image_from_base64(image):
|
| 297 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def expand2square(pil_img, background_color):
|
| 301 |
+
width, height = pil_img.size
|
| 302 |
+
if width == height:
|
| 303 |
+
return pil_img
|
| 304 |
+
elif width > height:
|
| 305 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 306 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 307 |
+
return result
|
| 308 |
+
else:
|
| 309 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 310 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 311 |
+
return result
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def process_images(images, image_processor, model_cfg):
|
| 315 |
+
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
| 316 |
+
new_images = []
|
| 317 |
+
if image_aspect_ratio == "highres":
|
| 318 |
+
for image in images:
|
| 319 |
+
image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
| 320 |
+
new_images.append(image)
|
| 321 |
+
elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
|
| 322 |
+
for image in images:
|
| 323 |
+
image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
|
| 324 |
+
new_images.append(image)
|
| 325 |
+
elif image_aspect_ratio == "crop_split":
|
| 326 |
+
for image in images:
|
| 327 |
+
image = process_highres_image_crop_split(image, model_cfg, image_processor)
|
| 328 |
+
new_images.append(image)
|
| 329 |
+
elif image_aspect_ratio == "pad":
|
| 330 |
+
for image in images:
|
| 331 |
+
image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
|
| 332 |
+
image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
|
| 333 |
+
new_images.append(image)
|
| 334 |
+
else:
|
| 335 |
+
return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
|
| 336 |
+
if all(x.shape == new_images[0].shape for x in new_images):
|
| 337 |
+
new_images = torch.stack(new_images, dim=0)
|
| 338 |
+
return new_images
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
| 342 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
|
| 343 |
+
|
| 344 |
+
def insert_separator(X, sep):
|
| 345 |
+
return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
|
| 346 |
+
|
| 347 |
+
input_ids = []
|
| 348 |
+
offset = 0
|
| 349 |
+
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
| 350 |
+
offset = 1
|
| 351 |
+
input_ids.append(prompt_chunks[0][0])
|
| 352 |
+
|
| 353 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
| 354 |
+
input_ids.extend(x[offset:])
|
| 355 |
+
|
| 356 |
+
if return_tensors is not None:
|
| 357 |
+
if return_tensors == "pt":
|
| 358 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
| 359 |
+
raise ValueError(f"Unsupported tensor type: {return_tensors}")
|
| 360 |
+
return input_ids
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def get_model_name_from_path(model_path):
|
| 364 |
+
model_path = model_path.strip("/")
|
| 365 |
+
model_paths = model_path.split("/")
|
| 366 |
+
if model_paths[-1].startswith("checkpoint-"):
|
| 367 |
+
return model_paths[-2] + "_" + model_paths[-1]
|
| 368 |
+
else:
|
| 369 |
+
return model_paths[-1]
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 373 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
| 374 |
+
self.keywords = keywords
|
| 375 |
+
self.keyword_ids = []
|
| 376 |
+
for keyword in keywords:
|
| 377 |
+
cur_keyword_ids = tokenizer(keyword).input_ids
|
| 378 |
+
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
| 379 |
+
cur_keyword_ids = cur_keyword_ids[1:]
|
| 380 |
+
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
| 381 |
+
self.tokenizer = tokenizer
|
| 382 |
+
self.start_len = input_ids.shape[1]
|
| 383 |
+
|
| 384 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 385 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
| 386 |
+
offset = min(output_ids.shape[1] - self.start_len, 3)
|
| 387 |
+
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
| 388 |
+
for keyword_id in self.keyword_ids:
|
| 389 |
+
if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
|
| 390 |
+
return True
|
| 391 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
| 392 |
+
for keyword in self.keywords:
|
| 393 |
+
if keyword in outputs:
|
| 394 |
+
return True
|
| 395 |
+
return False
|
spatial-model/VLM-3R/llava/model/multimodal_spatial_encoder/builder.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
# Get the directory containing the current script
|
| 5 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 6 |
+
# Go up four levels to reach VLM-3R/
|
| 7 |
+
vlm_3r_root = os.path.abspath(os.path.join(script_dir, '..', '..', '..'))
|
| 8 |
+
|
| 9 |
+
def build_spatial_tower(spatial_tower_cfg, **kwargs):
|
| 10 |
+
spatial_tower = getattr(spatial_tower_cfg, "mm_spatial_tower", getattr(spatial_tower_cfg, "spatial_tower", 'spann3r'))
|
| 11 |
+
if spatial_tower == "spann3r":
|
| 12 |
+
spann3r_path = os.path.join(vlm_3r_root, 'spann3r')
|
| 13 |
+
if spann3r_path not in sys.path:
|
| 14 |
+
sys.path.append(spann3r_path)
|
| 15 |
+
# Use relative import for the encoder wrapper/adapter file
|
| 16 |
+
from .spann3r_spatial_encoder import Spann3rSpatialTower
|
| 17 |
+
return Spann3rSpatialTower(spatial_tower, spatial_tower_cfg=spatial_tower_cfg, **kwargs)
|
| 18 |
+
elif spatial_tower == "cut3r":
|
| 19 |
+
cut3r_path = os.path.join(vlm_3r_root, 'CUT3R')
|
| 20 |
+
if cut3r_path not in sys.path:
|
| 21 |
+
sys.path.append(cut3r_path)
|
| 22 |
+
# Use relative import for the encoder wrapper/adapter file
|
| 23 |
+
from .cut3r_spatial_encoder import Cut3rSpatialTower
|
| 24 |
+
return Cut3rSpatialTower(spatial_tower, spatial_tower_cfg=spatial_tower_cfg, **kwargs)
|
| 25 |
+
elif spatial_tower == "vggt":
|
| 26 |
+
vggt_path = os.path.join(vlm_3r_root, 'vggt')
|
| 27 |
+
if vggt_path not in sys.path:
|
| 28 |
+
sys.path.append(vggt_path)
|
| 29 |
+
# Use relative import for the encoder wrapper/adapter file
|
| 30 |
+
from .vggt_spatial_encoder import VGGTSpatialTower
|
| 31 |
+
return VGGTSpatialTower(spatial_tower, spatial_tower_cfg=spatial_tower_cfg, **kwargs)
|
| 32 |
+
elif spatial_tower == "cut3r_points":
|
| 33 |
+
cut3r_path = os.path.join(vlm_3r_root, 'CUT3R') # Assumes cut3r_points is also in CUT3R
|
| 34 |
+
if cut3r_path not in sys.path:
|
| 35 |
+
sys.path.append(cut3r_path)
|
| 36 |
+
# Use relative import for the encoder wrapper/adapter file
|
| 37 |
+
from .cut3r_points import Cut3rPointsSpatialTower
|
| 38 |
+
return Cut3rPointsSpatialTower(spatial_tower, spatial_tower_cfg=spatial_tower_cfg, **kwargs)
|
| 39 |
+
raise ValueError(f"Unknown vision tower: {spatial_tower}")
|
spatial-model/VLM-3R/llava/model/multimodal_spatial_encoder/cut3r_points.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 4 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, BaseModelOutput
|
| 5 |
+
from typing import Union, Optional, Tuple
|
| 6 |
+
import os
|
| 7 |
+
from llava.utils import rank0_print
|
| 8 |
+
from einops import rearrange
|
| 9 |
+
from src.dust3r.model import ARCroco3DStereo
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
class Cut3rPointsConfig(PretrainedConfig):
|
| 13 |
+
model_type = "cut3r_points_model"
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
weights_path="../CUT3R/src/cut3r_512_dpt_4_64.pth",
|
| 18 |
+
**kwargs,
|
| 19 |
+
):
|
| 20 |
+
super().__init__(**kwargs)
|
| 21 |
+
self.weights_path = weights_path
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 25 |
+
cls._set_token_in_kwargs(kwargs)
|
| 26 |
+
|
| 27 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 28 |
+
|
| 29 |
+
# get the spatial config dict if we are loading from Cut3rSpatialConfig
|
| 30 |
+
if config_dict.get("model_type") == "cut3r_points":
|
| 31 |
+
config_dict = config_dict["spatial_config"]
|
| 32 |
+
|
| 33 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 34 |
+
print(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
|
| 35 |
+
|
| 36 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 37 |
+
|
| 38 |
+
class Cut3rPointsPreTrainedModel(PreTrainedModel):
|
| 39 |
+
"""
|
| 40 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 41 |
+
models.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
config_class = Cut3rPointsConfig
|
| 45 |
+
base_model_prefix = "cut3r"
|
| 46 |
+
supports_gradient_checkpointing = True
|
| 47 |
+
|
| 48 |
+
def _init_weights(self, module):
|
| 49 |
+
"""Initialize the weights"""
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
def prepare_input(pixel_values):
|
| 53 |
+
pixel_values = nn.functional.interpolate(pixel_values, size=(432, 432), mode='bilinear')
|
| 54 |
+
pixel_values = pixel_values.unsqueeze(1) ## FIXME: the second dimension is the number of frames in one batch
|
| 55 |
+
views = []
|
| 56 |
+
for i in range(len(pixel_values)):
|
| 57 |
+
view = {
|
| 58 |
+
"img": pixel_values[i],
|
| 59 |
+
"ray_map": torch.full(
|
| 60 |
+
(
|
| 61 |
+
pixel_values[i].shape[0],
|
| 62 |
+
6,
|
| 63 |
+
pixel_values[i].shape[-2],
|
| 64 |
+
pixel_values[i].shape[-1],
|
| 65 |
+
),
|
| 66 |
+
torch.nan,
|
| 67 |
+
).to(pixel_values[i].device),
|
| 68 |
+
"true_shape": torch.tensor(pixel_values[i].shape[-2:]).to(pixel_values[i].device),
|
| 69 |
+
"idx": i,
|
| 70 |
+
"instance": str(i),
|
| 71 |
+
"camera_pose": torch.eye(4).unsqueeze(0).to(pixel_values[i].device),
|
| 72 |
+
"img_mask": torch.tensor(True).unsqueeze(0).to(pixel_values[i].device),
|
| 73 |
+
"ray_mask": torch.tensor(False).unsqueeze(0).to(pixel_values[i].device),
|
| 74 |
+
"update": torch.tensor(True).unsqueeze(0).to(pixel_values[i].device),
|
| 75 |
+
"reset": torch.tensor(False).unsqueeze(0).to(pixel_values[i].device),
|
| 76 |
+
}
|
| 77 |
+
views.append(view)
|
| 78 |
+
return views
|
| 79 |
+
|
| 80 |
+
class Cut3rPointsEncoder(nn.Module):
|
| 81 |
+
def __init__(self, config: Cut3rPointsConfig, **kwargs):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.cut3r = ARCroco3DStereo.from_pretrained(config.weights_path)
|
| 84 |
+
self.cut3r.eval()
|
| 85 |
+
self.config = config
|
| 86 |
+
for param in self.cut3r.parameters():
|
| 87 |
+
param.requires_grad = False
|
| 88 |
+
|
| 89 |
+
def forward(
|
| 90 |
+
self,
|
| 91 |
+
pixel_values,
|
| 92 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 93 |
+
output_attentions: Optional[bool] = None,
|
| 94 |
+
output_hidden_states: Optional[bool] = None,
|
| 95 |
+
return_dict: Optional[bool] = None,
|
| 96 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 97 |
+
|
| 98 |
+
views = prepare_input(pixel_values=pixel_values)
|
| 99 |
+
shape, feat_ls, pos = self.cut3r._encode_views(views)
|
| 100 |
+
feat = feat_ls[-1]
|
| 101 |
+
state_feat, state_pos = self.cut3r._init_state(feat[0], pos[0])
|
| 102 |
+
mem = self.cut3r.pose_retriever.mem.expand(feat[0].shape[0], -1, -1)
|
| 103 |
+
init_state_feat = state_feat.clone()
|
| 104 |
+
init_mem = mem.clone()
|
| 105 |
+
all_state_args = [(state_feat, state_pos, init_state_feat, mem, init_mem)]
|
| 106 |
+
ress = []
|
| 107 |
+
out_points = []
|
| 108 |
+
for i in range(len(views)):
|
| 109 |
+
feat_i = feat[i].to(pixel_values.dtype)
|
| 110 |
+
pos_i = pos[i]
|
| 111 |
+
if self.cut3r.pose_head_flag:
|
| 112 |
+
global_img_feat_i = self.cut3r._get_img_level_feat(feat_i)
|
| 113 |
+
if i == 0:
|
| 114 |
+
pose_feat_i = self.cut3r.pose_token.expand(feat_i.shape[0], -1, -1)
|
| 115 |
+
else:
|
| 116 |
+
pose_feat_i = self.cut3r.pose_retriever.inquire(global_img_feat_i, mem)
|
| 117 |
+
pose_pos_i = -torch.ones(
|
| 118 |
+
feat_i.shape[0], 1, 2, device=feat_i.device, dtype=pos_i.dtype
|
| 119 |
+
)
|
| 120 |
+
else:
|
| 121 |
+
pose_feat_i = None
|
| 122 |
+
pose_pos_i = None
|
| 123 |
+
new_state_feat, dec = self.cut3r._recurrent_rollout(
|
| 124 |
+
state_feat,
|
| 125 |
+
state_pos,
|
| 126 |
+
feat_i,
|
| 127 |
+
pos_i,
|
| 128 |
+
pose_feat_i,
|
| 129 |
+
pose_pos_i,
|
| 130 |
+
init_state_feat,
|
| 131 |
+
img_mask=views[i]["img_mask"],
|
| 132 |
+
reset_mask=views[i]["reset"],
|
| 133 |
+
update=views[i].get("update", None),
|
| 134 |
+
)
|
| 135 |
+
out_pose_feat_i = dec[-1][:, 0:1]
|
| 136 |
+
new_mem = self.cut3r.pose_retriever.update_mem(
|
| 137 |
+
mem, global_img_feat_i, out_pose_feat_i
|
| 138 |
+
)
|
| 139 |
+
assert len(dec) == self.cut3r.dec_depth + 1
|
| 140 |
+
head_input = [
|
| 141 |
+
dec[0],
|
| 142 |
+
dec[self.cut3r.dec_depth * 2 // 4][:, 1:],
|
| 143 |
+
dec[self.cut3r.dec_depth * 3 // 4][:, 1:],
|
| 144 |
+
dec[self.cut3r.dec_depth],
|
| 145 |
+
]
|
| 146 |
+
res = self.cut3r._downstream_head(head_input, shape[i], pos=pos_i)
|
| 147 |
+
ress.append(res)
|
| 148 |
+
|
| 149 |
+
out_points.append(res["pts3d_in_other_view"])
|
| 150 |
+
img_mask = views[i]["img_mask"]
|
| 151 |
+
update = views[i].get("update", None)
|
| 152 |
+
if update is not None:
|
| 153 |
+
update_mask = (
|
| 154 |
+
img_mask & update
|
| 155 |
+
) # if don't update, then whatever img_mask
|
| 156 |
+
else:
|
| 157 |
+
update_mask = img_mask
|
| 158 |
+
update_mask = update_mask[:, None, None].to(pixel_values.dtype)
|
| 159 |
+
state_feat = new_state_feat * update_mask + state_feat * (
|
| 160 |
+
1 - update_mask
|
| 161 |
+
) # update global state
|
| 162 |
+
mem = new_mem * update_mask + mem * (
|
| 163 |
+
1 - update_mask
|
| 164 |
+
) # then update local state
|
| 165 |
+
reset_mask = views[i]["reset"]
|
| 166 |
+
if reset_mask is not None:
|
| 167 |
+
reset_mask = reset_mask[:, None, None].to(pixel_values.dtype)
|
| 168 |
+
state_feat = init_state_feat * reset_mask + state_feat * (
|
| 169 |
+
1 - reset_mask
|
| 170 |
+
)
|
| 171 |
+
mem = init_mem * reset_mask + mem * (1 - reset_mask)
|
| 172 |
+
all_state_args.append(
|
| 173 |
+
(state_feat, state_pos, init_state_feat, mem, init_mem)
|
| 174 |
+
)
|
| 175 |
+
# # for debug
|
| 176 |
+
# pts3d = []
|
| 177 |
+
# colors = []
|
| 178 |
+
# for i in range(len(views)):
|
| 179 |
+
# pts3d.append(ress[i]["pts3d_in_other_view"])
|
| 180 |
+
# colors.append(ress[i]["rgb"])
|
| 181 |
+
# pts3d = torch.cat(pts3d, dim=0) # b h w 3
|
| 182 |
+
# colors = torch.cat(colors, dim=0) # b h w 3
|
| 183 |
+
# pts3d = pts3d.view(-1, 3).float().cpu().numpy()
|
| 184 |
+
# colors = colors * 0.5 + 0.5
|
| 185 |
+
# colors = colors.view(-1, 3).float().cpu().numpy()
|
| 186 |
+
# #保存为点云
|
| 187 |
+
# import open3d as o3d
|
| 188 |
+
# pcd = o3d.geometry.PointCloud()
|
| 189 |
+
# pcd.points = o3d.utility.Vector3dVector(pts3d)
|
| 190 |
+
# pcd.colors = o3d.utility.Vector3dVector(colors)
|
| 191 |
+
# o3d.io.write_point_cloud("pts3d.ply", pcd)
|
| 192 |
+
|
| 193 |
+
out_points = torch.stack(out_points, dim=0) # [frame, b, H, W, 3]
|
| 194 |
+
out_points = rearrange(out_points, 'frame b H W c -> (b frame) H W c')
|
| 195 |
+
return out_points
|
| 196 |
+
|
| 197 |
+
class Cut3rPointsTransformer(nn.Module):
|
| 198 |
+
def __init__(self, config: Cut3rPointsConfig, **kwargs):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.config = config
|
| 201 |
+
self.encoder = Cut3rPointsEncoder(config=config, **kwargs)
|
| 202 |
+
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
pixel_values,
|
| 206 |
+
output_attentions: Optional[bool] = None,
|
| 207 |
+
output_hidden_states: Optional[bool] = None,
|
| 208 |
+
return_dict: Optional[bool] = None,
|
| 209 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 210 |
+
r"""
|
| 211 |
+
Returns:
|
| 212 |
+
|
| 213 |
+
"""
|
| 214 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 215 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 216 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 217 |
+
|
| 218 |
+
encoder_outputs = self.encoder(
|
| 219 |
+
pixel_values=pixel_values,
|
| 220 |
+
output_attentions=output_attentions,
|
| 221 |
+
output_hidden_states=output_hidden_states,
|
| 222 |
+
return_dict=return_dict,
|
| 223 |
+
)
|
| 224 |
+
return encoder_outputs
|
| 225 |
+
|
| 226 |
+
class Cut3rPointsSpatialModel(Cut3rPointsPreTrainedModel):
|
| 227 |
+
config_class = Cut3rPointsConfig
|
| 228 |
+
main_input_name = "pixel_values"
|
| 229 |
+
_no_split_modules = ["Cut3rPointsEncoderLayer"]
|
| 230 |
+
|
| 231 |
+
def __init__(self, config: Cut3rPointsConfig, **kwargs):
|
| 232 |
+
super().__init__(config)
|
| 233 |
+
|
| 234 |
+
self.spatial_model = Cut3rPointsTransformer(config, **kwargs)
|
| 235 |
+
|
| 236 |
+
# Initialize weights and apply final processing
|
| 237 |
+
self.post_init()
|
| 238 |
+
|
| 239 |
+
@classmethod
|
| 240 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], config: Cut3rPointsConfig, **kwargs):
|
| 241 |
+
model = cls(config=config, **kwargs)
|
| 242 |
+
return model
|
| 243 |
+
|
| 244 |
+
def forward(
|
| 245 |
+
self,
|
| 246 |
+
pixel_values,
|
| 247 |
+
output_attentions: Optional[bool] = None,
|
| 248 |
+
output_hidden_states: Optional[bool] = None,
|
| 249 |
+
return_dict: Optional[bool] = None,
|
| 250 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 251 |
+
|
| 252 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 253 |
+
|
| 254 |
+
return self.spatial_model(
|
| 255 |
+
pixel_values=pixel_values,
|
| 256 |
+
output_attentions=output_attentions,
|
| 257 |
+
output_hidden_states=output_hidden_states,
|
| 258 |
+
return_dict=return_dict,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
class Cut3rPointsSpatialTower(nn.Module):
|
| 262 |
+
def __init__(self, spatial_tower, spatial_tower_cfg, delay_load=True):
|
| 263 |
+
super().__init__()
|
| 264 |
+
|
| 265 |
+
self.is_loaded = False
|
| 266 |
+
|
| 267 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 268 |
+
vlm_3r_root = os.path.abspath(os.path.join(script_dir, '..', '..', '..'))
|
| 269 |
+
dynamic_weights_path = os.path.join(vlm_3r_root, 'CUT3R', 'src', 'cut3r_512_dpt_4_64.pth')
|
| 270 |
+
|
| 271 |
+
self.config = Cut3rPointsConfig(weights_path=dynamic_weights_path)
|
| 272 |
+
|
| 273 |
+
self.spatial_tower_name = spatial_tower
|
| 274 |
+
|
| 275 |
+
if not delay_load:
|
| 276 |
+
rank0_print(f"Loading spatial tower: {spatial_tower}")
|
| 277 |
+
self.load_model()
|
| 278 |
+
elif getattr(spatial_tower_cfg, "unfreeze_mm_spatial_tower", False):
|
| 279 |
+
# TODO: better detector is needed.
|
| 280 |
+
rank0_print(f"The checkpoint seems to contain `spatial_tower` weights: `unfreeze_mm_spatial_tower`: True.")
|
| 281 |
+
self.load_model()
|
| 282 |
+
elif hasattr(spatial_tower_cfg, "mm_tunable_parts") and "mm_spatial_tower" in spatial_tower_cfg.mm_tunable_parts:
|
| 283 |
+
rank0_print(f"The checkpoint seems to contain `spatial_tower` weights: `mm_tunable_parts` contains `mm_spatial_tower`.")
|
| 284 |
+
self.load_model()
|
| 285 |
+
else:
|
| 286 |
+
self.cfg_only = self.config
|
| 287 |
+
|
| 288 |
+
def load_model(self, device_map=None):
|
| 289 |
+
if self.is_loaded:
|
| 290 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.spatial_tower_name))
|
| 291 |
+
return
|
| 292 |
+
|
| 293 |
+
self.spatial_tower = Cut3rPointsSpatialModel.from_pretrained(self.spatial_tower_name, config=self.config, device_map=device_map)
|
| 294 |
+
|
| 295 |
+
self.spatial_tower.requires_grad_(False)
|
| 296 |
+
|
| 297 |
+
self.is_loaded = True
|
| 298 |
+
|
| 299 |
+
def forward(self, images):
|
| 300 |
+
if type(images) is list:
|
| 301 |
+
image_features = []
|
| 302 |
+
for image in images:
|
| 303 |
+
image_forward_out = self.spatial_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 304 |
+
image_feature = image_forward_out.last_hidden_state.to(image.dtype)
|
| 305 |
+
# assert image_features.shape[-2] == 729
|
| 306 |
+
image_features.append(image_feature)
|
| 307 |
+
else:
|
| 308 |
+
image_forward_outs = self.spatial_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 309 |
+
image_features = image_forward_outs.to(images.dtype)
|
| 310 |
+
# assert image_features.shape[-2] == 729
|
| 311 |
+
|
| 312 |
+
return image_features
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def dummy_feature(self):
|
| 316 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 317 |
+
|
| 318 |
+
@property
|
| 319 |
+
def dtype(self):
|
| 320 |
+
for p in self.spatial_tower.parameters():
|
| 321 |
+
return p.dtype
|
| 322 |
+
|
| 323 |
+
@property
|
| 324 |
+
def device(self):
|
| 325 |
+
for p in self.spatial_tower.parameters():
|
| 326 |
+
return p.device
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def hidden_size(self):
|
| 330 |
+
return self.config.hidden_size
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def num_patches(self):
|
| 334 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def num_patches_per_side(self):
|
| 338 |
+
return self.config.image_size // self.config.patch_size
|
| 339 |
+
|
| 340 |
+
@property
|
| 341 |
+
def image_size(self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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 4 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, BaseModelOutput
|
| 5 |
+
from typing import Union, Optional, Tuple
|
| 6 |
+
import os
|
| 7 |
+
from llava.utils import rank0_print
|
| 8 |
+
from einops import rearrange
|
| 9 |
+
import sys
|
| 10 |
+
sys.path.append('CUT3R')
|
| 11 |
+
from src.dust3r.model import ARCroco3DStereo
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import open3d as o3d
|
| 16 |
+
_OPEN3D_AVAILABLE = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
rank0_print("Warning: open3d not found. Point cloud export functionality will be disabled.")
|
| 19 |
+
_OPEN3D_AVAILABLE = False
|
| 20 |
+
|
| 21 |
+
class Cut3rSpatialConfig(PretrainedConfig):
|
| 22 |
+
model_type = "cut3r_spatial_model"
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
weights_path="../CUT3R/src/cut3r_512_dpt_4_64.pth",
|
| 27 |
+
spatial_tower_select_feature="patch",
|
| 28 |
+
spatial_tower_select_layer=-1,
|
| 29 |
+
export_point_cloud: bool = False,
|
| 30 |
+
point_cloud_output_dir: str = "point_clouds",
|
| 31 |
+
point_cloud_voxel_size: float = 0.02,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
super().__init__(**kwargs)
|
| 35 |
+
self.weights_path = weights_path
|
| 36 |
+
self.spatial_tower_select_feature = spatial_tower_select_feature
|
| 37 |
+
self.spatial_tower_select_layer = spatial_tower_select_layer
|
| 38 |
+
self.export_point_cloud = export_point_cloud
|
| 39 |
+
self.point_cloud_output_dir = point_cloud_output_dir
|
| 40 |
+
self.point_cloud_voxel_size = point_cloud_voxel_size
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 44 |
+
cls._set_token_in_kwargs(kwargs)
|
| 45 |
+
|
| 46 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 47 |
+
|
| 48 |
+
# get the spatial config dict if we are loading from Cut3rSpatialConfig
|
| 49 |
+
if config_dict.get("model_type") == "cut3r":
|
| 50 |
+
config_dict = config_dict["spatial_config"]
|
| 51 |
+
|
| 52 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 53 |
+
print(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
|
| 54 |
+
|
| 55 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 56 |
+
|
| 57 |
+
class Cut3rSpatialPreTrainedModel(PreTrainedModel):
|
| 58 |
+
"""
|
| 59 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 60 |
+
models.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
config_class = Cut3rSpatialConfig
|
| 64 |
+
base_model_prefix = "cut3r"
|
| 65 |
+
supports_gradient_checkpointing = True
|
| 66 |
+
|
| 67 |
+
def _init_weights(self, module):
|
| 68 |
+
"""Initialize the weights"""
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
def prepare_input(pixel_values):
|
| 72 |
+
pixel_values = nn.functional.interpolate(pixel_values, size=(432, 432), mode='bilinear')
|
| 73 |
+
pixel_values = pixel_values.unsqueeze(1) ## FIXME: the second dimension is the number of frames in one batch
|
| 74 |
+
views = []
|
| 75 |
+
# Assuming pixel_values is (F_max, B, C, H, W)
|
| 76 |
+
if not isinstance(pixel_values, torch.Tensor) or pixel_values.ndim != 5:
|
| 77 |
+
raise ValueError(f"Expected pixel_values to be a 5D tensor (F, B, C, H, W), got {type(pixel_values)} with shape {getattr(pixel_values, 'shape', 'N/A')}")
|
| 78 |
+
|
| 79 |
+
F_max, B, C, H, W = pixel_values.shape
|
| 80 |
+
device = pixel_values.device
|
| 81 |
+
|
| 82 |
+
for i in range(F_max):
|
| 83 |
+
current_frame_batch = pixel_values[i] # Shape (B, C, H, W)
|
| 84 |
+
view = {
|
| 85 |
+
"img": current_frame_batch,
|
| 86 |
+
"ray_map": torch.full(
|
| 87 |
+
(
|
| 88 |
+
B, # Use batch size B
|
| 89 |
+
6,
|
| 90 |
+
H, # Use H
|
| 91 |
+
W, # Use W
|
| 92 |
+
),
|
| 93 |
+
torch.nan,
|
| 94 |
+
).to(device),
|
| 95 |
+
"true_shape": torch.tensor([H, W], device=device).expand(B, -1), # Shape (B, 2)
|
| 96 |
+
"idx": i,
|
| 97 |
+
"instance": [str(j) for j in range(B)], # List of B instances
|
| 98 |
+
"camera_pose": torch.eye(4, device=device).unsqueeze(0).expand(B, -1, -1), # Shape (B, 4, 4)
|
| 99 |
+
"img_mask": torch.tensor(True, device=device).expand(B), # Shape (B)
|
| 100 |
+
"ray_mask": torch.tensor(False, device=device).expand(B), # Shape (B)
|
| 101 |
+
"update": torch.tensor(True, device=device).expand(B), # Shape (B)
|
| 102 |
+
"reset": torch.tensor(False, device=device).expand(B), # Shape (B)
|
| 103 |
+
}
|
| 104 |
+
views.append(view)
|
| 105 |
+
return views
|
| 106 |
+
|
| 107 |
+
class Cut3rEncoder(nn.Module):
|
| 108 |
+
def __init__(self, config: Cut3rSpatialConfig, **kwargs):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.cut3r = ARCroco3DStereo.from_pretrained(config.weights_path)
|
| 111 |
+
self.cut3r.eval()
|
| 112 |
+
self.config = config
|
| 113 |
+
for param in self.cut3r.parameters():
|
| 114 |
+
param.requires_grad = False
|
| 115 |
+
|
| 116 |
+
def export_point_cloud(self, views, ress, point_cloud_output_paths: Optional[list[str]]):
|
| 117 |
+
if not _OPEN3D_AVAILABLE:
|
| 118 |
+
rank0_print("Skipping point cloud export because open3d is not available.")
|
| 119 |
+
return
|
| 120 |
+
if not ress:
|
| 121 |
+
rank0_print("Warning: 'ress' list is empty, skipping point cloud export.")
|
| 122 |
+
return
|
| 123 |
+
if not point_cloud_output_paths:
|
| 124 |
+
rank0_print("Warning: point_cloud_output_paths is not provided. Skipping point cloud export.")
|
| 125 |
+
return
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
# Determine batch size (B) from the first frame's output if available
|
| 129 |
+
if 'pts3d_in_other_view' not in ress[0] or ress[0]['pts3d_in_other_view'] is None:
|
| 130 |
+
rank0_print("Warning: Cannot determine batch size from ress[0]. Skipping point cloud export.")
|
| 131 |
+
return
|
| 132 |
+
B = ress[0]['pts3d_in_other_view'].shape[0]
|
| 133 |
+
num_frames = len(views)
|
| 134 |
+
|
| 135 |
+
if len(point_cloud_output_paths) != B:
|
| 136 |
+
rank0_print(f"Warning: Number of output paths ({len(point_cloud_output_paths)}) does not match batch size ({B}). Skipping point cloud export.")
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
# Ensure base output directory exists (individual file paths might contain subdirs)
|
| 140 |
+
base_output_dir = os.path.dirname(point_cloud_output_paths[0])
|
| 141 |
+
if base_output_dir:
|
| 142 |
+
os.makedirs(base_output_dir, exist_ok=True)
|
| 143 |
+
|
| 144 |
+
for b_idx in range(B):
|
| 145 |
+
pts3d_batch_item = []
|
| 146 |
+
colors_batch_item = []
|
| 147 |
+
valid_frames_for_batch_item = 0
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
# Ensure the specific directory for this batch item exists
|
| 151 |
+
item_output_dir = os.path.dirname(point_cloud_output_paths[b_idx])
|
| 152 |
+
if item_output_dir:
|
| 153 |
+
os.makedirs(item_output_dir, exist_ok=True)
|
| 154 |
+
|
| 155 |
+
# --- Combine data across frames for the current batch item ---
|
| 156 |
+
for i in range(num_frames):
|
| 157 |
+
# Check if the tensors exist and have the expected batch dimension for this frame
|
| 158 |
+
if (i < len(ress) and
|
| 159 |
+
'pts3d_in_other_view' in ress[i] and
|
| 160 |
+
'rgb' in ress[i] and
|
| 161 |
+
ress[i]['pts3d_in_other_view'] is not None and
|
| 162 |
+
ress[i]['rgb'] is not None and
|
| 163 |
+
ress[i]['pts3d_in_other_view'].shape[0] == B and
|
| 164 |
+
ress[i]['rgb'].shape[0] == B):
|
| 165 |
+
|
| 166 |
+
# Extract data for the current batch item b_idx from frame i
|
| 167 |
+
pts3d_batch_item.append(ress[i]["pts3d_in_other_view"][b_idx]) # Shape (H, W, 3)
|
| 168 |
+
colors_batch_item.append(ress[i]["rgb"][b_idx]) # Shape (H, W, 3)
|
| 169 |
+
valid_frames_for_batch_item += 1
|
| 170 |
+
else:
|
| 171 |
+
rank0_print(f"Warning: Missing, None, or mismatched data in ress[{i}] for batch index {b_idx}. Skipping frame {i} for this item.")
|
| 172 |
+
# --- End combining data ---
|
| 173 |
+
|
| 174 |
+
if not pts3d_batch_item: # Skip if no valid frames found for this batch item
|
| 175 |
+
rank0_print(f"Warning: No valid frame data found for batch item {b_idx}. Skipping point cloud generation.")
|
| 176 |
+
continue # Skip to the next batch item
|
| 177 |
+
|
| 178 |
+
# Stack tensors from valid frames and reshape
|
| 179 |
+
# Stacking gives (F_valid, H, W, 3) -> view gives (F_valid*H*W, 3)
|
| 180 |
+
pts3d_single = torch.stack(pts3d_batch_item, dim=0).reshape(-1, 3).float().cpu().numpy()
|
| 181 |
+
colors_single_stacked = torch.stack(colors_batch_item, dim=0).reshape(-1, 3)
|
| 182 |
+
colors_single = (colors_single_stacked * 0.5 + 0.5).float().cpu().numpy() # Apply color transform
|
| 183 |
+
|
| 184 |
+
# Create Open3D point cloud for the item
|
| 185 |
+
pcd_item = o3d.geometry.PointCloud()
|
| 186 |
+
pcd_item.points = o3d.utility.Vector3dVector(pts3d_single)
|
| 187 |
+
pcd_item.colors = o3d.utility.Vector3dVector(colors_single)
|
| 188 |
+
|
| 189 |
+
# Voxel downsampling for the item
|
| 190 |
+
voxel_size = self.config.point_cloud_voxel_size
|
| 191 |
+
# rank0_print(f"Original combined point cloud (batch item {b_idx}) has {len(pcd_item.points)} points.")
|
| 192 |
+
downsampled_pcd_item = pcd_item.voxel_down_sample(voxel_size)
|
| 193 |
+
# rank0_print(f"Downsampled combined point cloud (batch item {b_idx}) has {len(downsampled_pcd_item.points)} points.")
|
| 194 |
+
|
| 195 |
+
# Save the downsampled point cloud for the item
|
| 196 |
+
output_path = point_cloud_output_paths[b_idx]
|
| 197 |
+
o3d.io.write_point_cloud(output_path, downsampled_pcd_item)
|
| 198 |
+
rank0_print(f"Saved combined and downsampled point cloud for batch item {b_idx} to {output_path}")
|
| 199 |
+
|
| 200 |
+
except (KeyError, IndexError, AttributeError, ValueError, RuntimeError, Exception) as item_e:
|
| 201 |
+
rank0_print(f"Error processing or saving point cloud for batch item {b_idx}: {item_e}")
|
| 202 |
+
import traceback
|
| 203 |
+
rank0_print(traceback.format_exc())
|
| 204 |
+
# Continue to the next batch item
|
| 205 |
+
|
| 206 |
+
except (KeyError, IndexError, AttributeError, ValueError, RuntimeError, Exception) as e:
|
| 207 |
+
rank0_print(f"Error during point cloud export setup (batch level): {e}")
|
| 208 |
+
import traceback
|
| 209 |
+
rank0_print(traceback.format_exc())
|
| 210 |
+
|
| 211 |
+
def forward(
|
| 212 |
+
self,
|
| 213 |
+
pixel_values,
|
| 214 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 215 |
+
output_attentions: Optional[bool] = None,
|
| 216 |
+
output_hidden_states: Optional[bool] = None,
|
| 217 |
+
return_dict: Optional[bool] = None,
|
| 218 |
+
point_cloud_output_paths: Optional[list[str]] = None
|
| 219 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 220 |
+
|
| 221 |
+
views = prepare_input(pixel_values=pixel_values)
|
| 222 |
+
shape, feat_ls, pos = self.cut3r._encode_views(views)
|
| 223 |
+
feat = feat_ls[-1]
|
| 224 |
+
state_feat, state_pos = self.cut3r._init_state(feat[0], pos[0])
|
| 225 |
+
mem = self.cut3r.pose_retriever.mem.expand(feat[0].shape[0], -1, -1)
|
| 226 |
+
init_state_feat = state_feat.clone()
|
| 227 |
+
init_mem = mem.clone()
|
| 228 |
+
all_state_args = [(state_feat, state_pos, init_state_feat, mem, init_mem)]
|
| 229 |
+
ress = []
|
| 230 |
+
# spatial_feat = []
|
| 231 |
+
patch_features = []
|
| 232 |
+
camera_tokens = []
|
| 233 |
+
for i in range(len(views)):
|
| 234 |
+
feat_i = feat[i].to(pixel_values.dtype)
|
| 235 |
+
pos_i = pos[i]
|
| 236 |
+
if self.cut3r.pose_head_flag:
|
| 237 |
+
global_img_feat_i = self.cut3r._get_img_level_feat(feat_i)
|
| 238 |
+
if i == 0:
|
| 239 |
+
pose_feat_i = self.cut3r.pose_token.expand(feat_i.shape[0], -1, -1)
|
| 240 |
+
else:
|
| 241 |
+
pose_feat_i = self.cut3r.pose_retriever.inquire(global_img_feat_i, mem)
|
| 242 |
+
pose_pos_i = -torch.ones(
|
| 243 |
+
feat_i.shape[0], 1, 2, device=feat_i.device, dtype=pos_i.dtype
|
| 244 |
+
)
|
| 245 |
+
else:
|
| 246 |
+
pose_feat_i = None
|
| 247 |
+
pose_pos_i = None
|
| 248 |
+
new_state_feat, dec = self.cut3r._recurrent_rollout(
|
| 249 |
+
state_feat,
|
| 250 |
+
state_pos,
|
| 251 |
+
feat_i,
|
| 252 |
+
pos_i,
|
| 253 |
+
pose_feat_i,
|
| 254 |
+
pose_pos_i,
|
| 255 |
+
init_state_feat,
|
| 256 |
+
img_mask=views[i]["img_mask"],
|
| 257 |
+
reset_mask=views[i]["reset"],
|
| 258 |
+
update=views[i].get("update", None),
|
| 259 |
+
)
|
| 260 |
+
out_pose_feat_i = dec[-1][:, 0:1]
|
| 261 |
+
new_mem = self.cut3r.pose_retriever.update_mem(
|
| 262 |
+
mem, global_img_feat_i, out_pose_feat_i
|
| 263 |
+
)
|
| 264 |
+
assert len(dec) == self.cut3r.dec_depth + 1
|
| 265 |
+
head_input = [
|
| 266 |
+
dec[0],
|
| 267 |
+
dec[self.cut3r.dec_depth * 2 // 4][:, 1:],
|
| 268 |
+
dec[self.cut3r.dec_depth * 3 // 4][:, 1:],
|
| 269 |
+
dec[self.cut3r.dec_depth],
|
| 270 |
+
]
|
| 271 |
+
res = self.cut3r._downstream_head(head_input, shape[i], pos=pos_i)
|
| 272 |
+
ress.append(res)
|
| 273 |
+
# # select feature
|
| 274 |
+
# if self.config.spatial_tower_select_feature == "patch":
|
| 275 |
+
# spatial_feat_layer = dec[int(self.config.spatial_tower_select_layer)][:, 1:]
|
| 276 |
+
# elif self.config.spatial_tower_select_feature == "all":
|
| 277 |
+
# spatial_feat_layer = dec[int(self.config.spatial_tower_select_layer)]
|
| 278 |
+
# else:
|
| 279 |
+
# raise ValueError(f"Unexpected spatial tower select feature: {self.config.spatial_tower_select_feature}")
|
| 280 |
+
# spatial_feat.append(spatial_feat_layer)
|
| 281 |
+
img_mask = views[i]["img_mask"]
|
| 282 |
+
update = views[i].get("update", None)
|
| 283 |
+
if update is not None:
|
| 284 |
+
update_mask = (
|
| 285 |
+
img_mask & update
|
| 286 |
+
) # if don't update, then whatever img_mask
|
| 287 |
+
else:
|
| 288 |
+
update_mask = img_mask
|
| 289 |
+
update_mask = update_mask[:, None, None].to(pixel_values.dtype)
|
| 290 |
+
state_feat = new_state_feat * update_mask + state_feat * (
|
| 291 |
+
1 - update_mask
|
| 292 |
+
) # update global state
|
| 293 |
+
mem = new_mem * update_mask + mem * (
|
| 294 |
+
1 - update_mask
|
| 295 |
+
) # then update local state
|
| 296 |
+
reset_mask = views[i]["reset"]
|
| 297 |
+
if reset_mask is not None:
|
| 298 |
+
reset_mask = reset_mask[:, None, None].to(pixel_values.dtype)
|
| 299 |
+
state_feat = init_state_feat * reset_mask + state_feat * (
|
| 300 |
+
1 - reset_mask
|
| 301 |
+
)
|
| 302 |
+
mem = init_mem * reset_mask + mem * (1 - reset_mask)
|
| 303 |
+
all_state_args.append(
|
| 304 |
+
(state_feat, state_pos, init_state_feat, mem, init_mem)
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# add camera token
|
| 308 |
+
camera_tokens.append(dec[-1][:, :1].clone())
|
| 309 |
+
# add patch features
|
| 310 |
+
patch_features.append(dec[-1][:, 1:].clone())
|
| 311 |
+
|
| 312 |
+
# # for debug - Modified for batch processing
|
| 313 |
+
# if not ress: # Handle empty ress case
|
| 314 |
+
# print("Warning: ress list is empty, skipping point cloud debug output.")
|
| 315 |
+
# B_debug = 0
|
| 316 |
+
# else:
|
| 317 |
+
# # Determine batch size (B) from the first element/frame's output
|
| 318 |
+
# # Assuming ress[0]['pts3d_in_other_view'] has shape (B, H, W, 3)
|
| 319 |
+
# B_debug = ress[0]['pts3d_in_other_view'].shape[0]
|
| 320 |
+
|
| 321 |
+
# for b_idx in range(B_debug):
|
| 322 |
+
# pts3d_batch_item = []
|
| 323 |
+
# colors_batch_item = []
|
| 324 |
+
# valid_frames_for_batch_item = 0
|
| 325 |
+
# for i in range(len(views)): # Iterate through frames (F_max)
|
| 326 |
+
# # Check if the tensors exist and have the expected batch dimension
|
| 327 |
+
# if (i < len(ress) and 'pts3d_in_other_view' in ress[i] and 'rgb' in ress[i] and
|
| 328 |
+
# ress[i]['pts3d_in_other_view'].shape[0] == B_debug and ress[i]['rgb'].shape[0] == B_debug):
|
| 329 |
+
# # Extract data for the current batch item b_idx
|
| 330 |
+
# pts3d_batch_item.append(ress[i]["pts3d_in_other_view"][b_idx]) # Shape (H, W, 3)
|
| 331 |
+
# colors_batch_item.append(ress[i]["rgb"][b_idx]) # Shape (H, W, 3)
|
| 332 |
+
# valid_frames_for_batch_item += 1
|
| 333 |
+
# else:
|
| 334 |
+
# print(f"Warning: Missing or mismatched data in ress[{i}] for batch index {b_idx}. Skipping frame {i} for this batch item.")
|
| 335 |
+
|
| 336 |
+
# if not pts3d_batch_item: # Skip if no valid frames found for this batch item
|
| 337 |
+
# print(f"Warning: No valid frame data found for batch item {b_idx}. Skipping point cloud generation.")
|
| 338 |
+
# continue
|
| 339 |
+
|
| 340 |
+
# # Concatenate across valid frames for this batch item
|
| 341 |
+
# # Need to stack along a new dimension (e.g., frame dim) then reshape, or cat along H/W dim if appropriate?
|
| 342 |
+
# # Original DUST3R might have concatenated along H or W. Let's assume stacking then view is safer.
|
| 343 |
+
# # Stacking gives (F_valid, H, W, 3) -> view gives (F_valid*H*W, 3)
|
| 344 |
+
# pts3d_single = torch.stack(pts3d_batch_item, dim=0).view(-1, 3).float().cpu().numpy()
|
| 345 |
+
# colors_single = torch.stack(colors_batch_item, dim=0).view(-1, 3)
|
| 346 |
+
# colors_single = (colors_single * 0.5 + 0.5).float().cpu().numpy() # Apply color transform
|
| 347 |
+
|
| 348 |
+
# # 保存为点云
|
| 349 |
+
# try:
|
| 350 |
+
# import open3d as o3d
|
| 351 |
+
# pcd = o3d.geometry.PointCloud()
|
| 352 |
+
# pcd.points = o3d.utility.Vector3dVector(pts3d_single)
|
| 353 |
+
# pcd.colors = o3d.utility.Vector3dVector(colors_single)
|
| 354 |
+
|
| 355 |
+
# # voxelize
|
| 356 |
+
# voxel_size = 0.05 # Example: 5cm voxel size
|
| 357 |
+
# # print(f"Original point cloud (batch item {b_idx}) has {len(pcd.points)} points.")
|
| 358 |
+
|
| 359 |
+
# # Apply voxel downsampling
|
| 360 |
+
# downsampled_pcd = pcd.voxel_down_sample(voxel_size)
|
| 361 |
+
# # print(f"Downsampled point cloud (batch item {b_idx}) has {len(downsampled_pcd.points)} points.")
|
| 362 |
+
|
| 363 |
+
# # Save the downsampled point cloud
|
| 364 |
+
# output_filename = f"downsampled_point_cloud_batch_{b_idx}.ply"
|
| 365 |
+
# o3d.io.write_point_cloud(output_filename, downsampled_pcd)
|
| 366 |
+
# # print(f"Saved point cloud for batch item {b_idx} to {output_filename}")
|
| 367 |
+
# except ImportError:
|
| 368 |
+
# print("Warning: open3d not found. Cannot save debug point cloud.")
|
| 369 |
+
# except Exception as e_pcd:
|
| 370 |
+
# print(f"Error processing or saving point cloud for batch item {b_idx}: {e_pcd}")
|
| 371 |
+
|
| 372 |
+
# spatial_feat = torch.stack(spatial_feat, dim=0) # [frame, b, token_num, token_dim]
|
| 373 |
+
# spatial_feat = rearrange(spatial_feat, 'frame b token_num token_dim -> (b frame) token_num token_dim')
|
| 374 |
+
# return (spatial_feat, None, None, None)
|
| 375 |
+
|
| 376 |
+
# Export point cloud if enabled
|
| 377 |
+
if self.config.export_point_cloud:
|
| 378 |
+
# Pass the specific output paths for this batch
|
| 379 |
+
self.export_point_cloud(views, ress, point_cloud_output_paths)
|
| 380 |
+
|
| 381 |
+
# rearrange patch_features, camera_tokens, hidden_states
|
| 382 |
+
patch_features = torch.stack(patch_features, dim=0)
|
| 383 |
+
patch_features = rearrange(patch_features, 'frame batch token_num token_dim -> (batch frame) token_num token_dim')
|
| 384 |
+
camera_tokens = torch.stack(camera_tokens, dim=0)
|
| 385 |
+
camera_tokens = rearrange(camera_tokens, 'frame batch token_num token_dim-> (batch frame) token_num token_dim')
|
| 386 |
+
|
| 387 |
+
return (camera_tokens, patch_features)
|
| 388 |
+
|
| 389 |
+
class Cut3rSpatialTransformer(nn.Module):
|
| 390 |
+
def __init__(self, config: Cut3rSpatialConfig, **kwargs):
|
| 391 |
+
super().__init__()
|
| 392 |
+
self.config = config
|
| 393 |
+
self.encoder = Cut3rEncoder(config=config, **kwargs)
|
| 394 |
+
|
| 395 |
+
def forward(
|
| 396 |
+
self,
|
| 397 |
+
pixel_values,
|
| 398 |
+
output_attentions: Optional[bool] = None,
|
| 399 |
+
output_hidden_states: Optional[bool] = None,
|
| 400 |
+
return_dict: Optional[bool] = None,
|
| 401 |
+
point_cloud_output_paths: Optional[list[str]] = None
|
| 402 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 403 |
+
r"""
|
| 404 |
+
Returns:
|
| 405 |
+
|
| 406 |
+
"""
|
| 407 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 408 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 409 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 410 |
+
|
| 411 |
+
encoder_outputs = self.encoder(
|
| 412 |
+
pixel_values=pixel_values,
|
| 413 |
+
output_attentions=output_attentions,
|
| 414 |
+
output_hidden_states=output_hidden_states,
|
| 415 |
+
return_dict=return_dict,
|
| 416 |
+
point_cloud_output_paths=point_cloud_output_paths
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
return encoder_outputs
|
| 420 |
+
|
| 421 |
+
# last_hidden_state = encoder_outputs[0]
|
| 422 |
+
|
| 423 |
+
# if not return_dict:
|
| 424 |
+
# return (last_hidden_state, None) + encoder_outputs[1:]
|
| 425 |
+
|
| 426 |
+
# return BaseModelOutputWithPooling(
|
| 427 |
+
# last_hidden_state=last_hidden_state,
|
| 428 |
+
# pooler_output=None,
|
| 429 |
+
# hidden_states=None,
|
| 430 |
+
# attentions=None,
|
| 431 |
+
# )
|
| 432 |
+
|
| 433 |
+
class Cut3rSpatialModel(Cut3rSpatialPreTrainedModel):
|
| 434 |
+
config_class = Cut3rSpatialConfig
|
| 435 |
+
main_input_name = "pixel_values"
|
| 436 |
+
_no_split_modules = ["Cut3rSpatialEncoderLayer"]
|
| 437 |
+
|
| 438 |
+
def __init__(self, config: Cut3rSpatialConfig, **kwargs):
|
| 439 |
+
super().__init__(config)
|
| 440 |
+
|
| 441 |
+
self.spatial_model = Cut3rSpatialTransformer(config, **kwargs)
|
| 442 |
+
|
| 443 |
+
# Initialize weights and apply final processing
|
| 444 |
+
self.post_init()
|
| 445 |
+
|
| 446 |
+
@classmethod
|
| 447 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], config: Cut3rSpatialConfig, **kwargs):
|
| 448 |
+
model = cls(config=config, **kwargs)
|
| 449 |
+
return model
|
| 450 |
+
|
| 451 |
+
def forward(
|
| 452 |
+
self,
|
| 453 |
+
pixel_values,
|
| 454 |
+
output_attentions: Optional[bool] = None,
|
| 455 |
+
output_hidden_states: Optional[bool] = None,
|
| 456 |
+
return_dict: Optional[bool] = None,
|
| 457 |
+
point_cloud_output_paths: Optional[list[str]] = None
|
| 458 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 459 |
+
|
| 460 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 461 |
+
|
| 462 |
+
return self.spatial_model(
|
| 463 |
+
pixel_values=pixel_values,
|
| 464 |
+
output_attentions=output_attentions,
|
| 465 |
+
output_hidden_states=output_hidden_states,
|
| 466 |
+
return_dict=return_dict,
|
| 467 |
+
point_cloud_output_paths=point_cloud_output_paths
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
class Cut3rSpatialTower(nn.Module):
|
| 471 |
+
def __init__(self, spatial_tower, spatial_tower_cfg, delay_load=True):
|
| 472 |
+
super().__init__()
|
| 473 |
+
|
| 474 |
+
self.is_loaded = False
|
| 475 |
+
|
| 476 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 477 |
+
vlm_3r_root = os.path.abspath(os.path.join(script_dir, '..', '..', '..'))
|
| 478 |
+
dynamic_weights_path = os.path.join(vlm_3r_root, 'CUT3R', 'src', 'cut3r_512_dpt_4_64.pth')
|
| 479 |
+
|
| 480 |
+
self.config = Cut3rSpatialConfig(
|
| 481 |
+
weights_path=dynamic_weights_path,
|
| 482 |
+
spatial_tower_select_feature=getattr(spatial_tower_cfg, 'spatial_tower_select_feature', 'patch'),
|
| 483 |
+
spatial_tower_select_layer=getattr(spatial_tower_cfg, 'spatial_tower_select_layer', -1)
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
self.spatial_tower_name = spatial_tower
|
| 487 |
+
|
| 488 |
+
if not delay_load:
|
| 489 |
+
rank0_print(f"Loading spatial tower: {spatial_tower}")
|
| 490 |
+
self.load_model()
|
| 491 |
+
elif getattr(spatial_tower_cfg, "unfreeze_mm_spatial_tower", False):
|
| 492 |
+
# TODO: better detector is needed.
|
| 493 |
+
rank0_print(f"The checkpoint seems to contain `spatial_tower` weights: `unfreeze_mm_spatial_tower`: True.")
|
| 494 |
+
self.load_model()
|
| 495 |
+
elif hasattr(spatial_tower_cfg, "mm_tunable_parts") and "mm_spatial_tower" in spatial_tower_cfg.mm_tunable_parts:
|
| 496 |
+
rank0_print(f"The checkpoint seems to contain `spatial_tower` weights: `mm_tunable_parts` contains `mm_spatial_tower`.")
|
| 497 |
+
self.load_model()
|
| 498 |
+
else:
|
| 499 |
+
self.cfg_only = self.config
|
| 500 |
+
|
| 501 |
+
def load_model(self, device_map=None):
|
| 502 |
+
if self.is_loaded:
|
| 503 |
+
rank0_print("{} is already loaded, `load_model` called again, skipping.".format(self.spatial_tower_name))
|
| 504 |
+
return
|
| 505 |
+
|
| 506 |
+
self.spatial_tower = Cut3rSpatialModel.from_pretrained(self.spatial_tower_name, config=self.config, device_map=device_map)
|
| 507 |
+
|
| 508 |
+
self.spatial_tower.requires_grad_(False)
|
| 509 |
+
|
| 510 |
+
self.is_loaded = True
|
| 511 |
+
|
| 512 |
+
def forward(self, images):
|
| 513 |
+
if type(images) is list:
|
| 514 |
+
image_features = []
|
| 515 |
+
for image in images:
|
| 516 |
+
image_forward_out = self.spatial_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 517 |
+
image_feature = image_forward_out.last_hidden_state.to(image.dtype)
|
| 518 |
+
# assert image_features.shape[-2] == 729
|
| 519 |
+
image_features.append(image_feature)
|
| 520 |
+
else:
|
| 521 |
+
image_features = self.spatial_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
|
| 522 |
+
# image_features = image_features_forward_out.to(images.dtype)
|
| 523 |
+
# assert image_features.shape[-2] == 729
|
| 524 |
+
|
| 525 |
+
return image_features
|
| 526 |
+
|
| 527 |
+
@property
|
| 528 |
+
def dummy_feature(self):
|
| 529 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 530 |
+
|
| 531 |
+
@property
|
| 532 |
+
def dtype(self):
|
| 533 |
+
for p in self.spatial_tower.parameters():
|
| 534 |
+
return p.dtype
|
| 535 |
+
|
| 536 |
+
@property
|
| 537 |
+
def device(self):
|
| 538 |
+
for p in self.spatial_tower.parameters():
|
| 539 |
+
return p.device
|
| 540 |
+
|
| 541 |
+
@property
|
| 542 |
+
def hidden_size(self):
|
| 543 |
+
return self.config.hidden_size
|
| 544 |
+
|
| 545 |
+
@property
|
| 546 |
+
def num_patches(self):
|
| 547 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
| 548 |
+
|
| 549 |
+
@property
|
| 550 |
+
def num_patches_per_side(self):
|
| 551 |
+
return self.config.image_size // self.config.patch_size
|
| 552 |
+
|
| 553 |
+
@property
|
| 554 |
+
def image_size(self):
|
| 555 |
+
return self.config.image_size
|
spatial-model/VLM-3R/llava/serve/__init__.py
ADDED
|
File without changes
|
spatial-model/VLM-3R/llava/serve/controller.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A controller manages distributed workers.
|
| 3 |
+
It sends worker addresses to clients.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import asyncio
|
| 8 |
+
import dataclasses
|
| 9 |
+
from enum import Enum, auto
|
| 10 |
+
import json
|
| 11 |
+
import logging
|
| 12 |
+
import time
|
| 13 |
+
from typing import List, Union
|
| 14 |
+
import threading
|
| 15 |
+
|
| 16 |
+
from fastapi import FastAPI, Request
|
| 17 |
+
from fastapi.responses import StreamingResponse
|
| 18 |
+
import numpy as np
|
| 19 |
+
import requests
|
| 20 |
+
import uvicorn
|
| 21 |
+
|
| 22 |
+
from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
|
| 23 |
+
from llava.utils import build_logger, server_error_msg
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = build_logger("controller", "controller.log")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DispatchMethod(Enum):
|
| 30 |
+
LOTTERY = auto()
|
| 31 |
+
SHORTEST_QUEUE = auto()
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_str(cls, name):
|
| 35 |
+
if name == "lottery":
|
| 36 |
+
return cls.LOTTERY
|
| 37 |
+
elif name == "shortest_queue":
|
| 38 |
+
return cls.SHORTEST_QUEUE
|
| 39 |
+
else:
|
| 40 |
+
raise ValueError(f"Invalid dispatch method")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclasses.dataclass
|
| 44 |
+
class WorkerInfo:
|
| 45 |
+
model_names: List[str]
|
| 46 |
+
speed: int
|
| 47 |
+
queue_length: int
|
| 48 |
+
check_heart_beat: bool
|
| 49 |
+
last_heart_beat: str
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def heart_beat_controller(controller):
|
| 53 |
+
while True:
|
| 54 |
+
time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
|
| 55 |
+
controller.remove_stable_workers_by_expiration()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Controller:
|
| 59 |
+
def __init__(self, dispatch_method: str):
|
| 60 |
+
# Dict[str -> WorkerInfo]
|
| 61 |
+
self.worker_info = {}
|
| 62 |
+
self.dispatch_method = DispatchMethod.from_str(dispatch_method)
|
| 63 |
+
|
| 64 |
+
self.heart_beat_thread = threading.Thread(target=heart_beat_controller, args=(self,))
|
| 65 |
+
self.heart_beat_thread.start()
|
| 66 |
+
|
| 67 |
+
logger.info("Init controller")
|
| 68 |
+
|
| 69 |
+
def register_worker(self, worker_name: str, check_heart_beat: bool, worker_status: dict):
|
| 70 |
+
if worker_name not in self.worker_info:
|
| 71 |
+
logger.info(f"Register a new worker: {worker_name}")
|
| 72 |
+
else:
|
| 73 |
+
logger.info(f"Register an existing worker: {worker_name}")
|
| 74 |
+
|
| 75 |
+
if not worker_status:
|
| 76 |
+
worker_status = self.get_worker_status(worker_name)
|
| 77 |
+
if not worker_status:
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
self.worker_info[worker_name] = WorkerInfo(worker_status["model_names"], worker_status["speed"], worker_status["queue_length"], check_heart_beat, time.time())
|
| 81 |
+
|
| 82 |
+
logger.info(f"Register done: {worker_name}, {worker_status}")
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
def get_worker_status(self, worker_name: str):
|
| 86 |
+
try:
|
| 87 |
+
r = requests.post(worker_name + "/worker_get_status", timeout=5)
|
| 88 |
+
except requests.exceptions.RequestException as e:
|
| 89 |
+
logger.error(f"Get status fails: {worker_name}, {e}")
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
if r.status_code != 200:
|
| 93 |
+
logger.error(f"Get status fails: {worker_name}, {r}")
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
return r.json()
|
| 97 |
+
|
| 98 |
+
def remove_worker(self, worker_name: str):
|
| 99 |
+
del self.worker_info[worker_name]
|
| 100 |
+
|
| 101 |
+
def refresh_all_workers(self):
|
| 102 |
+
old_info = dict(self.worker_info)
|
| 103 |
+
self.worker_info = {}
|
| 104 |
+
|
| 105 |
+
for w_name, w_info in old_info.items():
|
| 106 |
+
if not self.register_worker(w_name, w_info.check_heart_beat, None):
|
| 107 |
+
logger.info(f"Remove stale worker: {w_name}")
|
| 108 |
+
|
| 109 |
+
def list_models(self):
|
| 110 |
+
model_names = set()
|
| 111 |
+
|
| 112 |
+
for w_name, w_info in self.worker_info.items():
|
| 113 |
+
model_names.update(w_info.model_names)
|
| 114 |
+
|
| 115 |
+
return list(model_names)
|
| 116 |
+
|
| 117 |
+
def get_worker_address(self, model_name: str):
|
| 118 |
+
if self.dispatch_method == DispatchMethod.LOTTERY:
|
| 119 |
+
worker_names = []
|
| 120 |
+
worker_speeds = []
|
| 121 |
+
for w_name, w_info in self.worker_info.items():
|
| 122 |
+
if model_name in w_info.model_names:
|
| 123 |
+
worker_names.append(w_name)
|
| 124 |
+
worker_speeds.append(w_info.speed)
|
| 125 |
+
worker_speeds = np.array(worker_speeds, dtype=np.float32)
|
| 126 |
+
norm = np.sum(worker_speeds)
|
| 127 |
+
if norm < 1e-4:
|
| 128 |
+
return ""
|
| 129 |
+
worker_speeds = worker_speeds / norm
|
| 130 |
+
if True: # Directly return address
|
| 131 |
+
pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
|
| 132 |
+
worker_name = worker_names[pt]
|
| 133 |
+
return worker_name
|
| 134 |
+
|
| 135 |
+
# Check status before returning
|
| 136 |
+
while True:
|
| 137 |
+
pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
|
| 138 |
+
worker_name = worker_names[pt]
|
| 139 |
+
|
| 140 |
+
if self.get_worker_status(worker_name):
|
| 141 |
+
break
|
| 142 |
+
else:
|
| 143 |
+
self.remove_worker(worker_name)
|
| 144 |
+
worker_speeds[pt] = 0
|
| 145 |
+
norm = np.sum(worker_speeds)
|
| 146 |
+
if norm < 1e-4:
|
| 147 |
+
return ""
|
| 148 |
+
worker_speeds = worker_speeds / norm
|
| 149 |
+
continue
|
| 150 |
+
return worker_name
|
| 151 |
+
elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
|
| 152 |
+
worker_names = []
|
| 153 |
+
worker_qlen = []
|
| 154 |
+
for w_name, w_info in self.worker_info.items():
|
| 155 |
+
if model_name in w_info.model_names:
|
| 156 |
+
worker_names.append(w_name)
|
| 157 |
+
worker_qlen.append(w_info.queue_length / w_info.speed)
|
| 158 |
+
if len(worker_names) == 0:
|
| 159 |
+
return ""
|
| 160 |
+
min_index = np.argmin(worker_qlen)
|
| 161 |
+
w_name = worker_names[min_index]
|
| 162 |
+
self.worker_info[w_name].queue_length += 1
|
| 163 |
+
logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
|
| 164 |
+
return w_name
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
|
| 167 |
+
|
| 168 |
+
def receive_heart_beat(self, worker_name: str, queue_length: int):
|
| 169 |
+
if worker_name not in self.worker_info:
|
| 170 |
+
logger.info(f"Receive unknown heart beat. {worker_name}")
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
self.worker_info[worker_name].queue_length = queue_length
|
| 174 |
+
self.worker_info[worker_name].last_heart_beat = time.time()
|
| 175 |
+
logger.info(f"Receive heart beat. {worker_name}")
|
| 176 |
+
return True
|
| 177 |
+
|
| 178 |
+
def remove_stable_workers_by_expiration(self):
|
| 179 |
+
expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
|
| 180 |
+
to_delete = []
|
| 181 |
+
for worker_name, w_info in self.worker_info.items():
|
| 182 |
+
if w_info.check_heart_beat and w_info.last_heart_beat < expire:
|
| 183 |
+
to_delete.append(worker_name)
|
| 184 |
+
|
| 185 |
+
for worker_name in to_delete:
|
| 186 |
+
self.remove_worker(worker_name)
|
| 187 |
+
|
| 188 |
+
def worker_api_generate_stream(self, params):
|
| 189 |
+
worker_addr = self.get_worker_address(params["model"])
|
| 190 |
+
if not worker_addr:
|
| 191 |
+
logger.info(f"no worker: {params['model']}")
|
| 192 |
+
ret = {
|
| 193 |
+
"text": server_error_msg,
|
| 194 |
+
"error_code": 2,
|
| 195 |
+
}
|
| 196 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 197 |
+
|
| 198 |
+
try:
|
| 199 |
+
response = requests.post(worker_addr + "/worker_generate_stream", json=params, stream=True, timeout=5)
|
| 200 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 201 |
+
if chunk:
|
| 202 |
+
yield chunk + b"\0"
|
| 203 |
+
except requests.exceptions.RequestException as e:
|
| 204 |
+
logger.info(f"worker timeout: {worker_addr}")
|
| 205 |
+
ret = {
|
| 206 |
+
"text": server_error_msg,
|
| 207 |
+
"error_code": 3,
|
| 208 |
+
}
|
| 209 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 210 |
+
|
| 211 |
+
# Let the controller act as a worker to achieve hierarchical
|
| 212 |
+
# management. This can be used to connect isolated sub networks.
|
| 213 |
+
def worker_api_get_status(self):
|
| 214 |
+
model_names = set()
|
| 215 |
+
speed = 0
|
| 216 |
+
queue_length = 0
|
| 217 |
+
|
| 218 |
+
for w_name in self.worker_info:
|
| 219 |
+
worker_status = self.get_worker_status(w_name)
|
| 220 |
+
if worker_status is not None:
|
| 221 |
+
model_names.update(worker_status["model_names"])
|
| 222 |
+
speed += worker_status["speed"]
|
| 223 |
+
queue_length += worker_status["queue_length"]
|
| 224 |
+
|
| 225 |
+
return {
|
| 226 |
+
"model_names": list(model_names),
|
| 227 |
+
"speed": speed,
|
| 228 |
+
"queue_length": queue_length,
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
app = FastAPI()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.post("/register_worker")
|
| 236 |
+
async def register_worker(request: Request):
|
| 237 |
+
data = await request.json()
|
| 238 |
+
controller.register_worker(data["worker_name"], data["check_heart_beat"], data.get("worker_status", None))
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@app.post("/refresh_all_workers")
|
| 242 |
+
async def refresh_all_workers():
|
| 243 |
+
models = controller.refresh_all_workers()
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@app.post("/list_models")
|
| 247 |
+
async def list_models():
|
| 248 |
+
models = controller.list_models()
|
| 249 |
+
return {"models": models}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@app.post("/get_worker_address")
|
| 253 |
+
async def get_worker_address(request: Request):
|
| 254 |
+
data = await request.json()
|
| 255 |
+
addr = controller.get_worker_address(data["model"])
|
| 256 |
+
return {"address": addr}
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@app.post("/receive_heart_beat")
|
| 260 |
+
async def receive_heart_beat(request: Request):
|
| 261 |
+
data = await request.json()
|
| 262 |
+
exist = controller.receive_heart_beat(data["worker_name"], data["queue_length"])
|
| 263 |
+
return {"exist": exist}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@app.post("/worker_generate_stream")
|
| 267 |
+
async def worker_api_generate_stream(request: Request):
|
| 268 |
+
params = await request.json()
|
| 269 |
+
generator = controller.worker_api_generate_stream(params)
|
| 270 |
+
return StreamingResponse(generator)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@app.post("/worker_get_status")
|
| 274 |
+
async def worker_api_get_status(request: Request):
|
| 275 |
+
return controller.worker_api_get_status()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
parser = argparse.ArgumentParser()
|
| 280 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 281 |
+
parser.add_argument("--port", type=int, default=21001)
|
| 282 |
+
parser.add_argument("--dispatch-method", type=str, choices=["lottery", "shortest_queue"], default="shortest_queue")
|
| 283 |
+
args = parser.parse_args()
|
| 284 |
+
logger.info(f"args: {args}")
|
| 285 |
+
|
| 286 |
+
controller = Controller(args.dispatch_method)
|
| 287 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
spatial-model/VLM-3R/llava/serve/gradio_web_server.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import datetime
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import requests
|
| 9 |
+
|
| 10 |
+
from llava.conversation import default_conversation, conv_templates, SeparatorStyle
|
| 11 |
+
from llava.constants import LOGDIR
|
| 12 |
+
from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg
|
| 13 |
+
import hashlib
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = build_logger("gradio_web_server", "gradio_web_server.log")
|
| 17 |
+
|
| 18 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 19 |
+
|
| 20 |
+
no_change_btn = gr.Button.update()
|
| 21 |
+
enable_btn = gr.Button.update(interactive=True)
|
| 22 |
+
disable_btn = gr.Button.update(interactive=False)
|
| 23 |
+
|
| 24 |
+
priority = {
|
| 25 |
+
"vicuna-13b": "aaaaaaa",
|
| 26 |
+
"koala-13b": "aaaaaab",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_conv_log_filename():
|
| 31 |
+
t = datetime.datetime.now()
|
| 32 |
+
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
|
| 33 |
+
return name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_model_list():
|
| 37 |
+
ret = requests.post(args.controller_url + "/refresh_all_workers")
|
| 38 |
+
assert ret.status_code == 200
|
| 39 |
+
ret = requests.post(args.controller_url + "/list_models")
|
| 40 |
+
models = ret.json()["models"]
|
| 41 |
+
models.sort(key=lambda x: priority.get(x, x))
|
| 42 |
+
logger.info(f"Models: {models}")
|
| 43 |
+
return models
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
get_window_url_params = """
|
| 47 |
+
function() {
|
| 48 |
+
const params = new URLSearchParams(window.location.search);
|
| 49 |
+
url_params = Object.fromEntries(params);
|
| 50 |
+
console.log(url_params);
|
| 51 |
+
return url_params;
|
| 52 |
+
}
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_demo(url_params, request: gr.Request):
|
| 57 |
+
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
|
| 58 |
+
|
| 59 |
+
dropdown_update = gr.Dropdown.update(visible=True)
|
| 60 |
+
if "model" in url_params:
|
| 61 |
+
model = url_params["model"]
|
| 62 |
+
if model in models:
|
| 63 |
+
dropdown_update = gr.Dropdown.update(value=model, visible=True)
|
| 64 |
+
|
| 65 |
+
state = default_conversation.copy()
|
| 66 |
+
return state, dropdown_update
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def load_demo_refresh_model_list(request: gr.Request):
|
| 70 |
+
logger.info(f"load_demo. ip: {request.client.host}")
|
| 71 |
+
models = get_model_list()
|
| 72 |
+
state = default_conversation.copy()
|
| 73 |
+
dropdown_update = gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else "")
|
| 74 |
+
return state, dropdown_update
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
|
| 78 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 79 |
+
data = {
|
| 80 |
+
"tstamp": round(time.time(), 4),
|
| 81 |
+
"type": vote_type,
|
| 82 |
+
"model": model_selector,
|
| 83 |
+
"state": state.dict(),
|
| 84 |
+
"ip": request.client.host,
|
| 85 |
+
}
|
| 86 |
+
fout.write(json.dumps(data) + "\n")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def upvote_last_response(state, model_selector, request: gr.Request):
|
| 90 |
+
logger.info(f"upvote. ip: {request.client.host}")
|
| 91 |
+
vote_last_response(state, "upvote", model_selector, request)
|
| 92 |
+
return ("",) + (disable_btn,) * 3
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def downvote_last_response(state, model_selector, request: gr.Request):
|
| 96 |
+
logger.info(f"downvote. ip: {request.client.host}")
|
| 97 |
+
vote_last_response(state, "downvote", model_selector, request)
|
| 98 |
+
return ("",) + (disable_btn,) * 3
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def flag_last_response(state, model_selector, request: gr.Request):
|
| 102 |
+
logger.info(f"flag. ip: {request.client.host}")
|
| 103 |
+
vote_last_response(state, "flag", model_selector, request)
|
| 104 |
+
return ("",) + (disable_btn,) * 3
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def regenerate(state, image_process_mode, request: gr.Request):
|
| 108 |
+
logger.info(f"regenerate. ip: {request.client.host}")
|
| 109 |
+
state.messages[-1][-1] = None
|
| 110 |
+
prev_human_msg = state.messages[-2]
|
| 111 |
+
if type(prev_human_msg[1]) in (tuple, list):
|
| 112 |
+
prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
|
| 113 |
+
state.skip_next = False
|
| 114 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def clear_history(request: gr.Request):
|
| 118 |
+
logger.info(f"clear_history. ip: {request.client.host}")
|
| 119 |
+
state = default_conversation.copy()
|
| 120 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def add_text(state, text, image, image_process_mode, request: gr.Request):
|
| 124 |
+
logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
|
| 125 |
+
if len(text) <= 0 and image is None:
|
| 126 |
+
state.skip_next = True
|
| 127 |
+
return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
|
| 128 |
+
if args.moderate:
|
| 129 |
+
flagged = violates_moderation(text)
|
| 130 |
+
if flagged:
|
| 131 |
+
state.skip_next = True
|
| 132 |
+
return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
|
| 133 |
+
|
| 134 |
+
text = text[:1536] # Hard cut-off
|
| 135 |
+
if image is not None:
|
| 136 |
+
text = text[:1200] # Hard cut-off for images
|
| 137 |
+
if "<image>" not in text:
|
| 138 |
+
# text = '<Image><image></Image>' + text
|
| 139 |
+
text = text + "\n<image>"
|
| 140 |
+
text = (text, image, image_process_mode)
|
| 141 |
+
if len(state.get_images(return_pil=True)) > 0:
|
| 142 |
+
state = default_conversation.copy()
|
| 143 |
+
state.append_message(state.roles[0], text)
|
| 144 |
+
state.append_message(state.roles[1], None)
|
| 145 |
+
state.skip_next = False
|
| 146 |
+
return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request, template_name=None):
|
| 150 |
+
logger.info(f"http_bot. ip: {request.client.host}")
|
| 151 |
+
start_tstamp = time.time()
|
| 152 |
+
model_name = model_selector
|
| 153 |
+
|
| 154 |
+
if state.skip_next:
|
| 155 |
+
# This generate call is skipped due to invalid inputs
|
| 156 |
+
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
if len(state.messages) == state.offset + 2:
|
| 160 |
+
# First round of conversation
|
| 161 |
+
if "llava" in model_name.lower():
|
| 162 |
+
if "llama-2" in model_name.lower():
|
| 163 |
+
template_name = "llava_llama_2"
|
| 164 |
+
elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
|
| 165 |
+
if "orca" in model_name.lower():
|
| 166 |
+
template_name = "mistral_orca"
|
| 167 |
+
elif "hermes" in model_name.lower():
|
| 168 |
+
template_name = "mistral_direct"
|
| 169 |
+
else:
|
| 170 |
+
template_name = "mistral_instruct"
|
| 171 |
+
elif "zephyr" in model_name.lower():
|
| 172 |
+
template_name = "mistral_zephyr"
|
| 173 |
+
elif "hermes" in model_name.lower():
|
| 174 |
+
template_name = "mistral_direct"
|
| 175 |
+
elif "v1" in model_name.lower():
|
| 176 |
+
if "mmtag" in model_name.lower():
|
| 177 |
+
template_name = "llava_v1_mmtag"
|
| 178 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 179 |
+
template_name = "llava_v1_mmtag"
|
| 180 |
+
else:
|
| 181 |
+
template_name = "llava_v1"
|
| 182 |
+
elif "mpt" in model_name.lower():
|
| 183 |
+
template_name = "mpt"
|
| 184 |
+
else:
|
| 185 |
+
if "mmtag" in model_name.lower():
|
| 186 |
+
template_name = "v0_plain"
|
| 187 |
+
elif "plain" in model_name.lower() and "finetune" not in model_name.lower():
|
| 188 |
+
template_name = "v0_plain"
|
| 189 |
+
else:
|
| 190 |
+
template_name = "llava_v0"
|
| 191 |
+
elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
|
| 192 |
+
if "orca" in model_name.lower():
|
| 193 |
+
template_name = "mistral_orca"
|
| 194 |
+
elif "hermes" in model_name.lower():
|
| 195 |
+
template_name = "mistral_direct"
|
| 196 |
+
else:
|
| 197 |
+
template_name = "mistral_instruct"
|
| 198 |
+
elif "hermes" in model_name.lower():
|
| 199 |
+
template_name = "mistral_direct"
|
| 200 |
+
elif "zephyr" in model_name.lower():
|
| 201 |
+
template_name = "mistral_zephyr"
|
| 202 |
+
elif "mpt" in model_name:
|
| 203 |
+
template_name = "mpt_text"
|
| 204 |
+
elif "llama-2" in model_name:
|
| 205 |
+
template_name = "llama_2"
|
| 206 |
+
else:
|
| 207 |
+
template_name = "vicuna_v1"
|
| 208 |
+
new_state = conv_templates[template_name].copy()
|
| 209 |
+
new_state.append_message(new_state.roles[0], state.messages[-2][1])
|
| 210 |
+
new_state.append_message(new_state.roles[1], None)
|
| 211 |
+
state = new_state
|
| 212 |
+
|
| 213 |
+
# Query worker address
|
| 214 |
+
controller_url = args.controller_url
|
| 215 |
+
ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name})
|
| 216 |
+
worker_addr = ret.json()["address"]
|
| 217 |
+
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
|
| 218 |
+
|
| 219 |
+
# No available worker
|
| 220 |
+
if worker_addr == "":
|
| 221 |
+
state.messages[-1][-1] = server_error_msg
|
| 222 |
+
yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 223 |
+
return
|
| 224 |
+
|
| 225 |
+
# Construct prompt
|
| 226 |
+
prompt = state.get_prompt()
|
| 227 |
+
|
| 228 |
+
all_images = state.get_images(return_pil=True)
|
| 229 |
+
all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
|
| 230 |
+
for image, hash in zip(all_images, all_image_hash):
|
| 231 |
+
t = datetime.datetime.now()
|
| 232 |
+
filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
|
| 233 |
+
if not os.path.isfile(filename):
|
| 234 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 235 |
+
image.save(filename)
|
| 236 |
+
|
| 237 |
+
# Make requests
|
| 238 |
+
pload = {
|
| 239 |
+
"model": model_name,
|
| 240 |
+
"prompt": prompt,
|
| 241 |
+
"temperature": float(temperature),
|
| 242 |
+
"top_p": float(top_p),
|
| 243 |
+
"max_new_tokens": min(int(max_new_tokens), 1536),
|
| 244 |
+
"stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
|
| 245 |
+
"images": f"List of {len(state.get_images())} images: {all_image_hash}",
|
| 246 |
+
}
|
| 247 |
+
logger.info(f"==== request ====\n{pload}")
|
| 248 |
+
|
| 249 |
+
pload["images"] = state.get_images()
|
| 250 |
+
|
| 251 |
+
state.messages[-1][-1] = "▌"
|
| 252 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 253 |
+
|
| 254 |
+
try:
|
| 255 |
+
# Stream output
|
| 256 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=100)
|
| 257 |
+
last_print_time = time.time()
|
| 258 |
+
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
| 259 |
+
if chunk:
|
| 260 |
+
data = json.loads(chunk.decode())
|
| 261 |
+
if data["error_code"] == 0:
|
| 262 |
+
output = data["text"][len(prompt) :].strip()
|
| 263 |
+
state.messages[-1][-1] = output + "▌"
|
| 264 |
+
if time.time() - last_print_time > 0.05:
|
| 265 |
+
last_print_time = time.time()
|
| 266 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
|
| 267 |
+
else:
|
| 268 |
+
output = data["text"] + f" (error_code: {data['error_code']})"
|
| 269 |
+
state.messages[-1][-1] = output
|
| 270 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 271 |
+
return
|
| 272 |
+
time.sleep(0.03)
|
| 273 |
+
except requests.exceptions.RequestException as e:
|
| 274 |
+
state.messages[-1][-1] = server_error_msg
|
| 275 |
+
yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
state.messages[-1][-1] = state.messages[-1][-1][:-1]
|
| 279 |
+
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
|
| 280 |
+
|
| 281 |
+
finish_tstamp = time.time()
|
| 282 |
+
logger.info(f"{output}")
|
| 283 |
+
|
| 284 |
+
with open(get_conv_log_filename(), "a") as fout:
|
| 285 |
+
data = {
|
| 286 |
+
"tstamp": round(finish_tstamp, 4),
|
| 287 |
+
"type": "chat",
|
| 288 |
+
"model": model_name,
|
| 289 |
+
"start": round(start_tstamp, 4),
|
| 290 |
+
"finish": round(start_tstamp, 4),
|
| 291 |
+
"state": state.dict(),
|
| 292 |
+
"images": all_image_hash,
|
| 293 |
+
"ip": request.client.host,
|
| 294 |
+
}
|
| 295 |
+
fout.write(json.dumps(data) + "\n")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
title_markdown = """
|
| 299 |
+
# 🌋 LLaVA: Large Language and Vision Assistant
|
| 300 |
+
[[Project Page](https://llava-vl.github.io)] [[Code](https://github.com/haotian-liu/LLaVA)] [[Model](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)] | 📚 [[LLaVA](https://arxiv.org/abs/2304.08485)] [[LLaVA-v1.5](https://arxiv.org/abs/2310.03744)]
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
tos_markdown = """
|
| 304 |
+
### Terms of use
|
| 305 |
+
By using this service, users are required to agree to the following terms:
|
| 306 |
+
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.
|
| 307 |
+
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
|
| 308 |
+
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
learn_more_markdown = """
|
| 313 |
+
### License
|
| 314 |
+
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.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
block_css = """
|
| 318 |
+
|
| 319 |
+
#buttons button {
|
| 320 |
+
min-width: min(120px,100%);
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def build_demo(embed_mode):
|
| 327 |
+
textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
|
| 328 |
+
with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
|
| 329 |
+
state = gr.State()
|
| 330 |
+
|
| 331 |
+
if not embed_mode:
|
| 332 |
+
gr.Markdown(title_markdown)
|
| 333 |
+
|
| 334 |
+
with gr.Row():
|
| 335 |
+
with gr.Column(scale=3):
|
| 336 |
+
with gr.Row(elem_id="model_selector_row"):
|
| 337 |
+
model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False)
|
| 338 |
+
|
| 339 |
+
imagebox = gr.Image(type="pil")
|
| 340 |
+
image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False)
|
| 341 |
+
|
| 342 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
| 343 |
+
gr.Examples(
|
| 344 |
+
examples=[
|
| 345 |
+
[f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
|
| 346 |
+
[f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
|
| 347 |
+
],
|
| 348 |
+
inputs=[imagebox, textbox],
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
with gr.Accordion("Parameters", open=False) as parameter_row:
|
| 352 |
+
temperature = gr.Slider(
|
| 353 |
+
minimum=0.0,
|
| 354 |
+
maximum=1.0,
|
| 355 |
+
value=0.2,
|
| 356 |
+
step=0.1,
|
| 357 |
+
interactive=True,
|
| 358 |
+
label="Temperature",
|
| 359 |
+
)
|
| 360 |
+
top_p = gr.Slider(
|
| 361 |
+
minimum=0.0,
|
| 362 |
+
maximum=1.0,
|
| 363 |
+
value=0.7,
|
| 364 |
+
step=0.1,
|
| 365 |
+
interactive=True,
|
| 366 |
+
label="Top P",
|
| 367 |
+
)
|
| 368 |
+
max_output_tokens = gr.Slider(
|
| 369 |
+
minimum=0,
|
| 370 |
+
maximum=1024,
|
| 371 |
+
value=512,
|
| 372 |
+
step=64,
|
| 373 |
+
interactive=True,
|
| 374 |
+
label="Max output tokens",
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
with gr.Column(scale=8):
|
| 378 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550)
|
| 379 |
+
with gr.Row():
|
| 380 |
+
with gr.Column(scale=8):
|
| 381 |
+
textbox.render()
|
| 382 |
+
with gr.Column(scale=1, min_width=50):
|
| 383 |
+
submit_btn = gr.Button(value="Send", variant="primary")
|
| 384 |
+
with gr.Row(elem_id="buttons") as button_row:
|
| 385 |
+
upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
|
| 386 |
+
downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
|
| 387 |
+
flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
|
| 388 |
+
# stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
|
| 389 |
+
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
|
| 390 |
+
clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
|
| 391 |
+
|
| 392 |
+
if not embed_mode:
|
| 393 |
+
gr.Markdown(tos_markdown)
|
| 394 |
+
gr.Markdown(learn_more_markdown)
|
| 395 |
+
url_params = gr.JSON(visible=False)
|
| 396 |
+
|
| 397 |
+
# Register listeners
|
| 398 |
+
btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
|
| 399 |
+
upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 400 |
+
downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 401 |
+
flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False)
|
| 402 |
+
|
| 403 |
+
regenerate_btn.click(regenerate, [state, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list)
|
| 404 |
+
|
| 405 |
+
clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list, queue=False)
|
| 406 |
+
|
| 407 |
+
textbox.submit(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
|
| 408 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
submit_btn.click(add_text, [state, textbox, imagebox, image_process_mode], [state, chatbot, textbox, imagebox] + btn_list, queue=False).then(
|
| 412 |
+
http_bot, [state, model_selector, temperature, top_p, max_output_tokens], [state, chatbot] + btn_list
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
if args.model_list_mode == "once":
|
| 416 |
+
demo.load(load_demo, [url_params], [state, model_selector], _js=get_window_url_params, queue=False)
|
| 417 |
+
elif args.model_list_mode == "reload":
|
| 418 |
+
demo.load(load_demo_refresh_model_list, None, [state, model_selector], queue=False)
|
| 419 |
+
else:
|
| 420 |
+
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
|
| 421 |
+
|
| 422 |
+
return demo
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
if __name__ == "__main__":
|
| 426 |
+
parser = argparse.ArgumentParser()
|
| 427 |
+
parser.add_argument("--host", type=str, default="0.0.0.0")
|
| 428 |
+
parser.add_argument("--port", type=int)
|
| 429 |
+
parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
|
| 430 |
+
parser.add_argument("--concurrency-count", type=int, default=10)
|
| 431 |
+
parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"])
|
| 432 |
+
parser.add_argument("--share", action="store_true")
|
| 433 |
+
parser.add_argument("--moderate", action="store_true")
|
| 434 |
+
parser.add_argument("--embed", action="store_true")
|
| 435 |
+
args = parser.parse_args()
|
| 436 |
+
logger.info(f"args: {args}")
|
| 437 |
+
|
| 438 |
+
models = get_model_list()
|
| 439 |
+
|
| 440 |
+
logger.info(args)
|
| 441 |
+
demo = build_demo(args.embed)
|
| 442 |
+
demo.queue(concurrency_count=args.concurrency_count, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share)
|
spatial-model/VLM-3R/llava/serve/register_worker.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Manually register workers.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument("--controller-address", type=str)
|
| 15 |
+
parser.add_argument("--worker-name", type=str)
|
| 16 |
+
parser.add_argument("--check-heart-beat", action="store_true")
|
| 17 |
+
args = parser.parse_args()
|
| 18 |
+
|
| 19 |
+
url = args.controller_address + "/register_worker"
|
| 20 |
+
data = {
|
| 21 |
+
"worker_name": args.worker_name,
|
| 22 |
+
"check_heart_beat": args.check_heart_beat,
|
| 23 |
+
"worker_status": None,
|
| 24 |
+
}
|
| 25 |
+
r = requests.post(url, json=data)
|
| 26 |
+
assert r.status_code == 200
|
spatial-model/VLM-3R/llava/serve/sglang_worker.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A model worker executes the model.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
import threading
|
| 11 |
+
import uuid
|
| 12 |
+
|
| 13 |
+
from fastapi import FastAPI, Request, BackgroundTasks
|
| 14 |
+
from fastapi.responses import StreamingResponse
|
| 15 |
+
import requests
|
| 16 |
+
import re
|
| 17 |
+
import uvicorn
|
| 18 |
+
from functools import partial
|
| 19 |
+
|
| 20 |
+
from llava.constants import WORKER_HEART_BEAT_INTERVAL
|
| 21 |
+
from llava.utils import build_logger, server_error_msg, pretty_print_semaphore
|
| 22 |
+
from llava.model.builder import load_pretrained_model
|
| 23 |
+
from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
|
| 24 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 25 |
+
from transformers import AutoTokenizer
|
| 26 |
+
|
| 27 |
+
import sglang as sgl
|
| 28 |
+
from sglang.test.test_utils import add_common_sglang_args_and_parse, select_sglang_backend
|
| 29 |
+
from sglang.backend.runtime_endpoint import RuntimeEndpoint
|
| 30 |
+
from sglang.utils import read_jsonl, dump_state_text
|
| 31 |
+
from sglang.lang.interpreter import ProgramState
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
GB = 1 << 30
|
| 35 |
+
|
| 36 |
+
worker_id = str(uuid.uuid4())[:6]
|
| 37 |
+
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
|
| 38 |
+
global_counter = 0
|
| 39 |
+
|
| 40 |
+
model_semaphore = None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def heart_beat_worker(controller):
|
| 44 |
+
while True:
|
| 45 |
+
time.sleep(WORKER_HEART_BEAT_INTERVAL)
|
| 46 |
+
controller.send_heart_beat()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@sgl.function
|
| 50 |
+
def pipeline(s, prompt, max_tokens):
|
| 51 |
+
for p in prompt:
|
| 52 |
+
if type(p) is str:
|
| 53 |
+
s += p
|
| 54 |
+
else:
|
| 55 |
+
s += sgl.image(p)
|
| 56 |
+
s += sgl.gen("response", max_tokens=max_tokens)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ModelWorker:
|
| 60 |
+
def __init__(self, controller_addr, worker_addr, sgl_endpoint, worker_id, no_register, model_name):
|
| 61 |
+
self.controller_addr = controller_addr
|
| 62 |
+
self.worker_addr = worker_addr
|
| 63 |
+
self.worker_id = worker_id
|
| 64 |
+
|
| 65 |
+
# Select backend
|
| 66 |
+
backend = RuntimeEndpoint(sgl_endpoint)
|
| 67 |
+
sgl.set_default_backend(backend)
|
| 68 |
+
model_path = backend.model_info["model_path"]
|
| 69 |
+
|
| 70 |
+
if model_path.endswith("/"):
|
| 71 |
+
model_path = model_path[:-1]
|
| 72 |
+
if model_name is None:
|
| 73 |
+
model_paths = model_path.split("/")
|
| 74 |
+
if model_paths[-1].startswith("checkpoint-"):
|
| 75 |
+
self.model_name = model_paths[-2] + "_" + model_paths[-1]
|
| 76 |
+
else:
|
| 77 |
+
self.model_name = model_paths[-1]
|
| 78 |
+
else:
|
| 79 |
+
self.model_name = model_name
|
| 80 |
+
|
| 81 |
+
logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
|
| 82 |
+
|
| 83 |
+
if not no_register:
|
| 84 |
+
self.register_to_controller()
|
| 85 |
+
self.heart_beat_thread = threading.Thread(target=heart_beat_worker, args=(self,))
|
| 86 |
+
self.heart_beat_thread.start()
|
| 87 |
+
|
| 88 |
+
def register_to_controller(self):
|
| 89 |
+
logger.info("Register to controller")
|
| 90 |
+
|
| 91 |
+
url = self.controller_addr + "/register_worker"
|
| 92 |
+
data = {"worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status()}
|
| 93 |
+
r = requests.post(url, json=data)
|
| 94 |
+
assert r.status_code == 200
|
| 95 |
+
|
| 96 |
+
def send_heart_beat(self):
|
| 97 |
+
logger.info(f"Send heart beat. Models: {[self.model_name]}. " f"Semaphore: {pretty_print_semaphore(model_semaphore)}. " f"global_counter: {global_counter}")
|
| 98 |
+
|
| 99 |
+
url = self.controller_addr + "/receive_heart_beat"
|
| 100 |
+
|
| 101 |
+
while True:
|
| 102 |
+
try:
|
| 103 |
+
ret = requests.post(url, json={"worker_name": self.worker_addr, "queue_length": self.get_queue_length()}, timeout=5)
|
| 104 |
+
exist = ret.json()["exist"]
|
| 105 |
+
break
|
| 106 |
+
except requests.exceptions.RequestException as e:
|
| 107 |
+
logger.error(f"heart beat error: {e}")
|
| 108 |
+
time.sleep(5)
|
| 109 |
+
|
| 110 |
+
if not exist:
|
| 111 |
+
self.register_to_controller()
|
| 112 |
+
|
| 113 |
+
def get_queue_length(self):
|
| 114 |
+
if model_semaphore is None:
|
| 115 |
+
return 0
|
| 116 |
+
else:
|
| 117 |
+
return args.limit_model_concurrency - model_semaphore._value + (len(model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
|
| 118 |
+
|
| 119 |
+
def get_status(self):
|
| 120 |
+
return {
|
| 121 |
+
"model_names": [self.model_name],
|
| 122 |
+
"speed": 1,
|
| 123 |
+
"queue_length": self.get_queue_length(),
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
async def generate_stream(self, params):
|
| 127 |
+
ori_prompt = prompt = params["prompt"]
|
| 128 |
+
images = params.get("images", None)
|
| 129 |
+
if images is not None and len(images) > 0:
|
| 130 |
+
if len(images) > 0:
|
| 131 |
+
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
|
| 132 |
+
raise ValueError("Number of images does not match number of <image> tokens in prompt")
|
| 133 |
+
|
| 134 |
+
images = [load_image_from_base64(image) for image in images]
|
| 135 |
+
# FIXME: hacky padding
|
| 136 |
+
images = [expand2square(image, tuple(int(x * 255) for x in [0.48145466, 0.4578275, 0.40821073])) for image in images]
|
| 137 |
+
|
| 138 |
+
# FIXME: for image-start/end token
|
| 139 |
+
# replace_token = DEFAULT_IMAGE_TOKEN
|
| 140 |
+
# if getattr(self.model.config, 'mm_use_im_start_end', False):
|
| 141 |
+
# replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
| 142 |
+
# prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 143 |
+
prompt = prompt.replace(" " + DEFAULT_IMAGE_TOKEN + "\n", DEFAULT_IMAGE_TOKEN)
|
| 144 |
+
prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
|
| 145 |
+
prompt = []
|
| 146 |
+
for i in range(len(prompt_split)):
|
| 147 |
+
prompt.append(prompt_split[i])
|
| 148 |
+
if i < len(images):
|
| 149 |
+
prompt.append(images[i])
|
| 150 |
+
else:
|
| 151 |
+
prompt = [prompt]
|
| 152 |
+
|
| 153 |
+
temperature = float(params.get("temperature", 1.0))
|
| 154 |
+
top_p = float(params.get("top_p", 1.0))
|
| 155 |
+
# max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
|
| 156 |
+
max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
|
| 157 |
+
stop_str = params.get("stop", None)
|
| 158 |
+
stop_str = [stop_str] if stop_str is not None else None
|
| 159 |
+
|
| 160 |
+
if max_new_tokens < 1:
|
| 161 |
+
yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
# print(prompt)
|
| 165 |
+
state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True)
|
| 166 |
+
|
| 167 |
+
generated_text = ori_prompt
|
| 168 |
+
async for text_outputs in state.text_async_iter(var_name="response"):
|
| 169 |
+
generated_text += text_outputs
|
| 170 |
+
yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
|
| 171 |
+
|
| 172 |
+
async def generate_stream_gate(self, params):
|
| 173 |
+
try:
|
| 174 |
+
async for x in self.generate_stream(params):
|
| 175 |
+
yield x
|
| 176 |
+
except ValueError as e:
|
| 177 |
+
print("Caught ValueError:", e)
|
| 178 |
+
ret = {
|
| 179 |
+
"text": server_error_msg,
|
| 180 |
+
"error_code": 1,
|
| 181 |
+
}
|
| 182 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print("Caught Unknown Error", e)
|
| 185 |
+
ret = {
|
| 186 |
+
"text": server_error_msg,
|
| 187 |
+
"error_code": 1,
|
| 188 |
+
}
|
| 189 |
+
yield json.dumps(ret).encode() + b"\0"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
app = FastAPI()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def release_model_semaphore(fn=None):
|
| 196 |
+
model_semaphore.release()
|
| 197 |
+
if fn is not None:
|
| 198 |
+
fn()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@app.post("/worker_generate_stream")
|
| 202 |
+
async def generate_stream(request: Request):
|
| 203 |
+
global model_semaphore, global_counter
|
| 204 |
+
global_counter += 1
|
| 205 |
+
params = await request.json()
|
| 206 |
+
|
| 207 |
+
if model_semaphore is None:
|
| 208 |
+
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
|
| 209 |
+
await model_semaphore.acquire()
|
| 210 |
+
worker.send_heart_beat()
|
| 211 |
+
generator = worker.generate_stream_gate(params)
|
| 212 |
+
background_tasks = BackgroundTasks()
|
| 213 |
+
background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
|
| 214 |
+
return StreamingResponse(generator, background=background_tasks)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@app.post("/worker_get_status")
|
| 218 |
+
async def get_status(request: Request):
|
| 219 |
+
return worker.get_status()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if __name__ == "__main__":
|
| 223 |
+
parser = argparse.ArgumentParser()
|
| 224 |
+
parser.add_argument("--host", type=str, default="localhost")
|
| 225 |
+
parser.add_argument("--port", type=int, default=21002)
|
| 226 |
+
parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
|
| 227 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 228 |
+
parser.add_argument("--model-name", type=str)
|
| 229 |
+
parser.add_argument("--sgl-endpoint", type=str)
|
| 230 |
+
parser.add_argument("--limit-model-concurrency", type=int, default=5)
|
| 231 |
+
parser.add_argument("--stream-interval", type=int, default=1)
|
| 232 |
+
parser.add_argument("--no-register", action="store_true")
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
logger.info(f"args: {args}")
|
| 235 |
+
|
| 236 |
+
worker = ModelWorker(args.controller_address, args.worker_address, args.sgl_endpoint, worker_id, args.no_register, args.model_name)
|
| 237 |
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
spatial-model/VLM-3R/llava/serve/test_message.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from llava.conversation import default_conversation
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
if args.worker_address:
|
| 11 |
+
worker_addr = args.worker_address
|
| 12 |
+
else:
|
| 13 |
+
controller_addr = args.controller_address
|
| 14 |
+
ret = requests.post(controller_addr + "/refresh_all_workers")
|
| 15 |
+
ret = requests.post(controller_addr + "/list_models")
|
| 16 |
+
models = ret.json()["models"]
|
| 17 |
+
models.sort()
|
| 18 |
+
print(f"Models: {models}")
|
| 19 |
+
|
| 20 |
+
ret = requests.post(controller_addr + "/get_worker_address", json={"model": args.model_name})
|
| 21 |
+
worker_addr = ret.json()["address"]
|
| 22 |
+
print(f"worker_addr: {worker_addr}")
|
| 23 |
+
|
| 24 |
+
if worker_addr == "":
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
conv = default_conversation.copy()
|
| 28 |
+
conv.append_message(conv.roles[0], args.message)
|
| 29 |
+
prompt = conv.get_prompt()
|
| 30 |
+
|
| 31 |
+
headers = {"User-Agent": "LLaVA Client"}
|
| 32 |
+
pload = {
|
| 33 |
+
"model": args.model_name,
|
| 34 |
+
"prompt": prompt,
|
| 35 |
+
"max_new_tokens": args.max_new_tokens,
|
| 36 |
+
"temperature": 0.7,
|
| 37 |
+
"stop": conv.sep,
|
| 38 |
+
}
|
| 39 |
+
response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True)
|
| 40 |
+
|
| 41 |
+
print(prompt.replace(conv.sep, "\n"), end="")
|
| 42 |
+
for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
|
| 43 |
+
if chunk:
|
| 44 |
+
data = json.loads(chunk.decode("utf-8"))
|
| 45 |
+
output = data["text"].split(conv.sep)[-1]
|
| 46 |
+
print(output, end="\r")
|
| 47 |
+
print("")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
parser = argparse.ArgumentParser()
|
| 52 |
+
parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
|
| 53 |
+
parser.add_argument("--worker-address", type=str)
|
| 54 |
+
parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
|
| 55 |
+
parser.add_argument("--max-new-tokens", type=int, default=32)
|
| 56 |
+
parser.add_argument("--message", type=str, default="Tell me a story with more than 1000 words.")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
main()
|
spatial-model/VLM-3R/llava/spar_utils.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 3 |
+
import cv2
|
| 4 |
+
|
| 5 |
+
def scale_bbox(bbox, width, height):
|
| 6 |
+
return (np.array(bbox[0]) / 1000) * np.array([width, height, width, height])
|
| 7 |
+
|
| 8 |
+
def scale_point(point, width, height):
|
| 9 |
+
return (np.array(point[0]) / 1000) * np.array([width, height])
|
| 10 |
+
|
| 11 |
+
def draw_points(draw, image, data_entry, points):
|
| 12 |
+
for color, key in points:
|
| 13 |
+
point = scale_point(data_entry[key], image.width, image.height)
|
| 14 |
+
point = tuple(map(int, point))
|
| 15 |
+
draw.ellipse([point[0]-20, point[1]-20, point[0]+20, point[1]+20], fill=color)
|
| 16 |
+
|
| 17 |
+
def draw_thick_bbox(draw, image, bbox, color, stroke=20):
|
| 18 |
+
bbox = scale_bbox(bbox, image.width, image.height)
|
| 19 |
+
extend = stroke * 7 / 8
|
| 20 |
+
bbox_out = [bbox[0] - extend, bbox[1] - extend, bbox[2] + extend, bbox[3] + extend]
|
| 21 |
+
draw.rectangle(tuple(map(int, bbox_out)), outline=color, width=stroke)
|
| 22 |
+
|
| 23 |
+
def draw_spatial_relation_oo(image, data_entry):
|
| 24 |
+
draw = ImageDraw.Draw(image)
|
| 25 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 26 |
+
draw_thick_bbox(draw, image, data_entry["blue_bbox"], "blue", stroke=20)
|
| 27 |
+
|
| 28 |
+
def draw_depth_prediction_oc(image, data_entry):
|
| 29 |
+
draw = ImageDraw.Draw(image)
|
| 30 |
+
draw_points(draw, image, data_entry, [("red", "red_point"), ("blue", "blue_point")])
|
| 31 |
+
|
| 32 |
+
def draw_depth_prediction_oo(image, data_entry):
|
| 33 |
+
draw = ImageDraw.Draw(image)
|
| 34 |
+
draw_points(draw, image, data_entry, [("red", "red_point"), ("blue", "blue_point"), ("green", "green_point")])
|
| 35 |
+
|
| 36 |
+
def draw_distance_prediction_oc(image, data_entry):
|
| 37 |
+
draw = ImageDraw.Draw(image)
|
| 38 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 39 |
+
|
| 40 |
+
def draw_distance_prediction_oo(image, data_entry):
|
| 41 |
+
draw = ImageDraw.Draw(image)
|
| 42 |
+
draw_points(draw, image, data_entry, [("red", "red_point"), ("blue", "blue_point")])
|
| 43 |
+
|
| 44 |
+
def draw_distance_inference_oc(image, data_entry):
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
def draw_distance_inference_oo(image, data_entry):
|
| 48 |
+
draw = ImageDraw.Draw(image)
|
| 49 |
+
draw_points(draw, image, data_entry, [("red", "red_point"), ("blue", "blue_point"), ("green", "green_point")])
|
| 50 |
+
|
| 51 |
+
def draw_spatial_volume_infer(image, data_entry):
|
| 52 |
+
draw = ImageDraw.Draw(image)
|
| 53 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 54 |
+
|
| 55 |
+
def draw_spatial_imagination_oc(image, data_entry):
|
| 56 |
+
draw = ImageDraw.Draw(image)
|
| 57 |
+
|
| 58 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 59 |
+
draw_thick_bbox(draw, image, data_entry["blue_bbox"], "blue", stroke=20)
|
| 60 |
+
draw_thick_bbox(draw, image, data_entry["green_bbox"], "green", stroke=20)
|
| 61 |
+
|
| 62 |
+
def draw_position_matching(images, data_entry):
|
| 63 |
+
image_to_draw = images[0]
|
| 64 |
+
draw = ImageDraw.Draw(image_to_draw)
|
| 65 |
+
|
| 66 |
+
draw_thick_bbox(draw, image_to_draw, data_entry["red_bbox"], "red", stroke=20)
|
| 67 |
+
|
| 68 |
+
def draw_spatial_imagination_oo(image, data_entry):
|
| 69 |
+
draw = ImageDraw.Draw(image)
|
| 70 |
+
|
| 71 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 72 |
+
draw_thick_bbox(draw, image, data_entry["blue_bbox"], "blue", stroke=20)
|
| 73 |
+
draw_thick_bbox(draw, image, data_entry["green_bbox"], "green", stroke=20)
|
| 74 |
+
draw_thick_bbox(draw, image, data_entry["yellow_bbox"], "yellow", stroke=20)
|
| 75 |
+
|
| 76 |
+
def draw_view_change_infer(images, data_entry):
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
def draw_depth_prediction_oc_mv(images, data_entry):
|
| 80 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 81 |
+
|
| 82 |
+
image = images[image_idx[0]]
|
| 83 |
+
draw = ImageDraw.Draw(image)
|
| 84 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 85 |
+
|
| 86 |
+
image = images[image_idx[1]]
|
| 87 |
+
draw = ImageDraw.Draw(image)
|
| 88 |
+
draw_points(draw, image, data_entry, [("blue", "blue_point")])
|
| 89 |
+
|
| 90 |
+
def draw_depth_prediction_oo_mv(images, data_entry):
|
| 91 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 92 |
+
|
| 93 |
+
image = images[image_idx[0]]
|
| 94 |
+
draw = ImageDraw.Draw(image)
|
| 95 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 96 |
+
|
| 97 |
+
image = images[image_idx[1]]
|
| 98 |
+
draw = ImageDraw.Draw(image)
|
| 99 |
+
draw_points(draw, image, data_entry, [("blue", "blue_point")])
|
| 100 |
+
|
| 101 |
+
image = images[image_idx[2]]
|
| 102 |
+
draw = ImageDraw.Draw(image)
|
| 103 |
+
draw_points(draw, image, data_entry, [("green", "green_point")])
|
| 104 |
+
|
| 105 |
+
def draw_distance_prediction_oc_mv(images, data_entry):
|
| 106 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 107 |
+
|
| 108 |
+
image = images[image_idx[0]]
|
| 109 |
+
draw = ImageDraw.Draw(image)
|
| 110 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 111 |
+
|
| 112 |
+
def draw_distance_prediction_oo_mv(images, data_entry):
|
| 113 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 114 |
+
|
| 115 |
+
image = images[image_idx[0]]
|
| 116 |
+
draw = ImageDraw.Draw(image)
|
| 117 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 118 |
+
|
| 119 |
+
image = images[image_idx[1]]
|
| 120 |
+
draw = ImageDraw.Draw(image)
|
| 121 |
+
draw_points(draw, image, data_entry, [("blue", "blue_point")])
|
| 122 |
+
|
| 123 |
+
def draw_obj_spatial_relation_oc_mv(images, data_entry):
|
| 124 |
+
image_idx = data_entry["bbox_img_idx"][0]
|
| 125 |
+
|
| 126 |
+
image = images[image_idx[0]]
|
| 127 |
+
draw = ImageDraw.Draw(image)
|
| 128 |
+
|
| 129 |
+
red_bbox = data_entry.get("red_bbox", None)
|
| 130 |
+
if red_bbox:
|
| 131 |
+
draw_thick_bbox(draw, image, red_bbox, "red", stroke=20)
|
| 132 |
+
|
| 133 |
+
blue_bbox = data_entry.get("blue_bbox", None)
|
| 134 |
+
if blue_bbox:
|
| 135 |
+
draw_thick_bbox(draw, image, blue_bbox, "blue", stroke=20)
|
| 136 |
+
|
| 137 |
+
green_bbox = data_entry.get("green_bbox", None)
|
| 138 |
+
if green_bbox:
|
| 139 |
+
draw_thick_bbox(draw, image, green_bbox, "green", stroke=20)
|
| 140 |
+
|
| 141 |
+
def draw_obj_spatial_relation_oo_mv(images, data_entry):
|
| 142 |
+
image_idx = data_entry["bbox_img_idx"][0]
|
| 143 |
+
red_bbox = data_entry.get("red_bbox", None)
|
| 144 |
+
blue_bbox = data_entry.get("blue_bbox", None)
|
| 145 |
+
green_bbox = data_entry.get("green_bbox", None)
|
| 146 |
+
if red_bbox is None:
|
| 147 |
+
image = images[image_idx[0]]
|
| 148 |
+
draw = ImageDraw.Draw(image)
|
| 149 |
+
draw_thick_bbox(draw, image, blue_bbox, "blue", stroke=20)
|
| 150 |
+
|
| 151 |
+
image = images[image_idx[1]]
|
| 152 |
+
draw = ImageDraw.Draw(image)
|
| 153 |
+
draw_thick_bbox(draw, image, green_bbox, "green", stroke=20)
|
| 154 |
+
elif blue_bbox is None:
|
| 155 |
+
image = images[image_idx[0]]
|
| 156 |
+
draw = ImageDraw.Draw(image)
|
| 157 |
+
draw_thick_bbox(draw, image, red_bbox, "red", stroke=20)
|
| 158 |
+
|
| 159 |
+
image = images[image_idx[1]]
|
| 160 |
+
draw = ImageDraw.Draw(image)
|
| 161 |
+
draw_thick_bbox(draw, image, green_bbox, "green", stroke=20)
|
| 162 |
+
elif green_bbox is None:
|
| 163 |
+
image = images[image_idx[0]]
|
| 164 |
+
draw = ImageDraw.Draw(image)
|
| 165 |
+
draw_thick_bbox(draw, image, red_bbox, "red", stroke=20)
|
| 166 |
+
|
| 167 |
+
image = images[image_idx[1]]
|
| 168 |
+
draw = ImageDraw.Draw(image)
|
| 169 |
+
draw_thick_bbox(draw, image, blue_bbox, "blue", stroke=20)
|
| 170 |
+
else:
|
| 171 |
+
raise ValueError("Unexpected data entry")
|
| 172 |
+
|
| 173 |
+
def draw_distance_infer_center_oc_mv(images, data_entry):
|
| 174 |
+
pass
|
| 175 |
+
|
| 176 |
+
def draw_distance_infer_center_oo_mv(images, data_entry):
|
| 177 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 178 |
+
|
| 179 |
+
image = images[image_idx[0]]
|
| 180 |
+
draw = ImageDraw.Draw(image)
|
| 181 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 182 |
+
|
| 183 |
+
image = images[image_idx[1]]
|
| 184 |
+
draw = ImageDraw.Draw(image)
|
| 185 |
+
draw_points(draw, image, data_entry, [("green", "green_point")])
|
| 186 |
+
|
| 187 |
+
image = images[image_idx[2]]
|
| 188 |
+
draw = ImageDraw.Draw(image)
|
| 189 |
+
draw_points(draw, image, data_entry, [("blue", "blue_point")])
|
| 190 |
+
|
| 191 |
+
def draw_spatial_imagination_oc_mv(images, data_entry):
|
| 192 |
+
image_idx = data_entry["bbox_img_idx"][0]
|
| 193 |
+
|
| 194 |
+
image = images[image_idx[2]]
|
| 195 |
+
draw = ImageDraw.Draw(image)
|
| 196 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 197 |
+
|
| 198 |
+
image = images[image_idx[0]]
|
| 199 |
+
draw = ImageDraw.Draw(image)
|
| 200 |
+
draw_thick_bbox(draw, image, data_entry["green_bbox"], "green", stroke=20)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
image = images[image_idx[1]]
|
| 204 |
+
draw = ImageDraw.Draw(image)
|
| 205 |
+
draw_thick_bbox(draw, image, data_entry["blue_bbox"], "blue", stroke=20)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def draw_spatial_imagination_oo_mv(images, data_entry):
|
| 209 |
+
image_idx = data_entry["bbox_img_idx"][0]
|
| 210 |
+
|
| 211 |
+
image = images[image_idx[2]]
|
| 212 |
+
draw = ImageDraw.Draw(image)
|
| 213 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 214 |
+
|
| 215 |
+
image = images[image_idx[0]]
|
| 216 |
+
draw = ImageDraw.Draw(image)
|
| 217 |
+
draw_thick_bbox(draw, image, data_entry["green_bbox"], "green", stroke=20)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
image = images[image_idx[1]]
|
| 221 |
+
draw = ImageDraw.Draw(image)
|
| 222 |
+
draw_thick_bbox(draw, image, data_entry["blue_bbox"], "blue", stroke=20)
|
| 223 |
+
|
| 224 |
+
image = images[image_idx[3]]
|
| 225 |
+
draw = ImageDraw.Draw(image)
|
| 226 |
+
draw_thick_bbox(draw, image, data_entry["yellow_bbox"], "yellow", stroke=20)
|
| 227 |
+
|
| 228 |
+
def draw_spatial_imagination_map_mv(images, data_entry):
|
| 229 |
+
for i, bbox in enumerate(data_entry["bbox_list"][0]):
|
| 230 |
+
img_idx = data_entry["bbox_img_idx"][0][i]
|
| 231 |
+
image = images[img_idx]
|
| 232 |
+
image = np.array(image)
|
| 233 |
+
|
| 234 |
+
bbox = (np.array(bbox) / 1000) * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]])
|
| 235 |
+
bbox = bbox.astype(int)
|
| 236 |
+
|
| 237 |
+
cv2.rectangle(image, (bbox[0]-20, bbox[1]-20), (bbox[2]+20, bbox[3]+20), color=(0, 0, 255), thickness=20)
|
| 238 |
+
|
| 239 |
+
label = f"object{i}"
|
| 240 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 241 |
+
font_scale = 2.0
|
| 242 |
+
thickness = 10
|
| 243 |
+
text_size, _ = cv2.getTextSize(label, font, font_scale, thickness)
|
| 244 |
+
|
| 245 |
+
text_position = (bbox[2] - text_size[0], bbox[3] + text_size[1])
|
| 246 |
+
if text_position[1] > image.shape[0]:
|
| 247 |
+
text_position = (bbox[2] - text_size[0], bbox[3] - text_size[1])
|
| 248 |
+
|
| 249 |
+
cv2.putText(image, label, text_position, font, font_scale, color=(0, 255, 0), thickness=thickness)
|
| 250 |
+
|
| 251 |
+
images[img_idx] = Image.fromarray(image)
|
| 252 |
+
|
| 253 |
+
def draw_distance_prediction_oo_video(images, data_entry):
|
| 254 |
+
image_idx = data_entry["point_img_idx"][0]
|
| 255 |
+
|
| 256 |
+
image = images[image_idx[0]]
|
| 257 |
+
draw = ImageDraw.Draw(image)
|
| 258 |
+
draw_points(draw, image, data_entry, [("red", "red_point")])
|
| 259 |
+
|
| 260 |
+
image = images[image_idx[1]]
|
| 261 |
+
draw = ImageDraw.Draw(image)
|
| 262 |
+
draw_points(draw, image, data_entry, [("blue", "blue_point")])
|
| 263 |
+
|
| 264 |
+
def draw_distance_infer_center_oo_video(images, data_entry):
|
| 265 |
+
for i, point in enumerate(data_entry["point_list"][0]):
|
| 266 |
+
img_idx = data_entry["point_img_idx"][0][i]
|
| 267 |
+
image = images[img_idx]
|
| 268 |
+
image = np.array(image)
|
| 269 |
+
|
| 270 |
+
point = (np.array(point) / 1000) * np.array([image.shape[1], image.shape[0]])
|
| 271 |
+
point = tuple(map(int, point))
|
| 272 |
+
|
| 273 |
+
cv2.circle(image, point, radius=20, color=(0, 0, 255), thickness=-1)
|
| 274 |
+
|
| 275 |
+
if i == 0:
|
| 276 |
+
label = f"objectA"
|
| 277 |
+
else:
|
| 278 |
+
label = f"object{i-1}"
|
| 279 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 280 |
+
font_scale = 2.0
|
| 281 |
+
thickness = 10
|
| 282 |
+
text_size, _ = cv2.getTextSize(label, font, font_scale, thickness)
|
| 283 |
+
|
| 284 |
+
text_position = (point[0] + 20, point[1] + 20)
|
| 285 |
+
|
| 286 |
+
cv2.putText(image, label, text_position, font, font_scale, color=(0, 255, 0), thickness=thickness)
|
| 287 |
+
|
| 288 |
+
images[img_idx] = Image.fromarray(image)
|
| 289 |
+
|
| 290 |
+
def draw_spatial_imagination_oo_video(images, data_entry):
|
| 291 |
+
image_indices = data_entry["bbox_img_idx"][0]
|
| 292 |
+
|
| 293 |
+
bboxes_info = [
|
| 294 |
+
{"bbox_key": "green_bbox", "color": (0, 255, 0), "label": "object0"},
|
| 295 |
+
{"bbox_key": "blue_bbox", "color": (255, 0, 0), "label": "object1"},
|
| 296 |
+
{"bbox_key": "red_bbox", "color": (0, 0, 255), "label": "object2"},
|
| 297 |
+
{"bbox_key": "yellow_bbox", "color": (225, 225, 0), "label": "object3"}
|
| 298 |
+
]
|
| 299 |
+
|
| 300 |
+
for i, bbox_info in enumerate(bboxes_info):
|
| 301 |
+
img_idx = image_indices[i]
|
| 302 |
+
image = images[img_idx]
|
| 303 |
+
|
| 304 |
+
if isinstance(image, Image.Image):
|
| 305 |
+
image_np = np.array(image)
|
| 306 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
| 307 |
+
else:
|
| 308 |
+
image_np = image
|
| 309 |
+
|
| 310 |
+
bbox = data_entry[bbox_info["bbox_key"]]
|
| 311 |
+
bbox_coords = (np.array(bbox[0]) / 1000) * np.array([image_np.shape[1], image_np.shape[0], image_np.shape[1], image_np.shape[0]])
|
| 312 |
+
bbox_coords = bbox_coords.astype(int)
|
| 313 |
+
bbox_tuple = tuple(bbox_coords)
|
| 314 |
+
|
| 315 |
+
cv2.rectangle(image_np,
|
| 316 |
+
(bbox_tuple[0]-20, bbox_tuple[1]-20),
|
| 317 |
+
(bbox_tuple[2]+20, bbox_tuple[3]+20),
|
| 318 |
+
color=bbox_info["color"],
|
| 319 |
+
thickness=20)
|
| 320 |
+
|
| 321 |
+
label = bbox_info["label"]
|
| 322 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 323 |
+
font_scale = 2.0
|
| 324 |
+
thickness_text = 10
|
| 325 |
+
text_size, _ = cv2.getTextSize(label, font, font_scale, thickness_text)
|
| 326 |
+
|
| 327 |
+
text_x = bbox_tuple[2] - text_size[0]
|
| 328 |
+
text_y = bbox_tuple[3] + text_size[1]
|
| 329 |
+
|
| 330 |
+
if text_y > image_np.shape[0]:
|
| 331 |
+
text_y = bbox_tuple[3] - 5
|
| 332 |
+
|
| 333 |
+
text_position = (text_x, text_y)
|
| 334 |
+
|
| 335 |
+
cv2.rectangle(image_np,
|
| 336 |
+
(text_x, text_y - text_size[1]),
|
| 337 |
+
(text_x + text_size[0], text_y + 5),
|
| 338 |
+
bbox_info["color"],
|
| 339 |
+
cv2.FILLED)
|
| 340 |
+
|
| 341 |
+
cv2.putText(image_np,
|
| 342 |
+
label,
|
| 343 |
+
text_position,
|
| 344 |
+
font,
|
| 345 |
+
font_scale,
|
| 346 |
+
(255, 255, 255),
|
| 347 |
+
thickness_text,
|
| 348 |
+
cv2.LINE_AA)
|
| 349 |
+
|
| 350 |
+
image_pil = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
|
| 351 |
+
images[img_idx] = image_pil
|
| 352 |
+
|
| 353 |
+
def draw_spatial_imagination_oc_video(images, data_entry):
|
| 354 |
+
image_indices = data_entry["bbox_img_idx"][0]
|
| 355 |
+
|
| 356 |
+
bboxes_info = [
|
| 357 |
+
{"bbox_key": "green_bbox", "color": (0, 255, 0), "label": "object0"},
|
| 358 |
+
{"bbox_key": "blue_bbox", "color": (255, 0, 0), "label": "object1"},
|
| 359 |
+
{"bbox_key": "red_bbox", "color": (0, 0, 255), "label": "object2"},
|
| 360 |
+
]
|
| 361 |
+
|
| 362 |
+
for i, bbox_info in enumerate(bboxes_info):
|
| 363 |
+
img_idx = image_indices[i]
|
| 364 |
+
image = images[img_idx]
|
| 365 |
+
|
| 366 |
+
if isinstance(image, Image.Image):
|
| 367 |
+
image_np = np.array(image)
|
| 368 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
| 369 |
+
else:
|
| 370 |
+
image_np = image
|
| 371 |
+
|
| 372 |
+
bbox = data_entry[bbox_info["bbox_key"]]
|
| 373 |
+
bbox_coords = (np.array(bbox[0]) / 1000) * np.array([image_np.shape[1], image_np.shape[0], image_np.shape[1], image_np.shape[0]])
|
| 374 |
+
bbox_coords = bbox_coords.astype(int)
|
| 375 |
+
bbox_tuple = tuple(bbox_coords)
|
| 376 |
+
|
| 377 |
+
cv2.rectangle(image_np,
|
| 378 |
+
(bbox_tuple[0]-20, bbox_tuple[1]-20),
|
| 379 |
+
(bbox_tuple[2]+20, bbox_tuple[3]+20),
|
| 380 |
+
color=bbox_info["color"],
|
| 381 |
+
thickness=20)
|
| 382 |
+
|
| 383 |
+
label = bbox_info["label"]
|
| 384 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 385 |
+
font_scale = 2.0
|
| 386 |
+
thickness_text = 10
|
| 387 |
+
text_size, _ = cv2.getTextSize(label, font, font_scale, thickness_text)
|
| 388 |
+
|
| 389 |
+
text_x = bbox_tuple[2] - text_size[0]
|
| 390 |
+
text_y = bbox_tuple[3] + text_size[1]
|
| 391 |
+
|
| 392 |
+
if text_y > image_np.shape[0]:
|
| 393 |
+
text_y = bbox_tuple[3] - 5
|
| 394 |
+
|
| 395 |
+
text_position = (text_x, text_y)
|
| 396 |
+
|
| 397 |
+
cv2.rectangle(image_np,
|
| 398 |
+
(text_x, text_y - text_size[1]),
|
| 399 |
+
(text_x + text_size[0], text_y + 5),
|
| 400 |
+
bbox_info["color"],
|
| 401 |
+
cv2.FILLED)
|
| 402 |
+
|
| 403 |
+
cv2.putText(image_np,
|
| 404 |
+
label,
|
| 405 |
+
text_position,
|
| 406 |
+
font,
|
| 407 |
+
font_scale,
|
| 408 |
+
(255, 255, 255),
|
| 409 |
+
thickness_text,
|
| 410 |
+
cv2.LINE_AA)
|
| 411 |
+
|
| 412 |
+
image_pil = Image.fromarray(cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB))
|
| 413 |
+
images[img_idx] = image_pil
|
| 414 |
+
|
| 415 |
+
def draw_obj_frame_locate(images, data_entry):
|
| 416 |
+
image_idx = data_entry["bbox_img_idx"][0]
|
| 417 |
+
|
| 418 |
+
image = images[image_idx[0]]
|
| 419 |
+
draw = ImageDraw.Draw(image)
|
| 420 |
+
draw_thick_bbox(draw, image, data_entry["red_bbox"], "red", stroke=20)
|
| 421 |
+
|
| 422 |
+
def draw_appearance_order(images, data_entry):
|
| 423 |
+
pass
|
| 424 |
+
|
| 425 |
+
def draw_room_size(images, data_entry):
|
| 426 |
+
pass
|
| 427 |
+
|
| 428 |
+
def draw_camera_motion_infer(images, data_entry):
|
| 429 |
+
pass
|
| 430 |
+
|
| 431 |
+
def draw_nav(images, data_entry):
|
| 432 |
+
pass
|
| 433 |
+
|
| 434 |
+
def draw_obj_count(images, data_entry):
|
| 435 |
+
pass
|
| 436 |
+
|
| 437 |
+
def draw_spatial_imagination_oc_video_hard(images, data_entry):
|
| 438 |
+
pass
|
| 439 |
+
|
| 440 |
+
def draw_spatial_imagination_oo_video_hard(images, data_entry):
|
| 441 |
+
pass
|
| 442 |
+
|
| 443 |
+
DRAW_FUNCTIONS = {
|
| 444 |
+
# Single View
|
| 445 |
+
"obj_spatial_relation_oo": draw_spatial_relation_oo,
|
| 446 |
+
"depth_prediction_oc": draw_depth_prediction_oc,
|
| 447 |
+
"depth_prediction_oo": draw_depth_prediction_oo,
|
| 448 |
+
"distance_prediction_oc": draw_distance_prediction_oc,
|
| 449 |
+
"distance_prediction_oo": draw_distance_prediction_oo,
|
| 450 |
+
"distance_infer_center_oc": draw_distance_inference_oc,
|
| 451 |
+
"distance_infer_center_oo": draw_distance_inference_oo,
|
| 452 |
+
"spatial_volume_infer": draw_spatial_volume_infer,
|
| 453 |
+
"spatial_imagination_oc": draw_spatial_imagination_oc,
|
| 454 |
+
"spatial_imagination_oo": draw_spatial_imagination_oo,
|
| 455 |
+
|
| 456 |
+
# Multi View
|
| 457 |
+
"position_matching": draw_position_matching,
|
| 458 |
+
"view_change_infer": draw_view_change_infer,
|
| 459 |
+
"depth_prediction_oc_mv": draw_depth_prediction_oc_mv,
|
| 460 |
+
"depth_prediction_oo_mv": draw_depth_prediction_oo_mv,
|
| 461 |
+
"distance_prediction_oc_mv": draw_distance_prediction_oc_mv,
|
| 462 |
+
"distance_prediction_oo_mv": draw_distance_prediction_oo_mv,
|
| 463 |
+
"obj_spatial_relation_oc_mv": draw_obj_spatial_relation_oc_mv,
|
| 464 |
+
"obj_spatial_relation_oo_mv": draw_obj_spatial_relation_oo_mv,
|
| 465 |
+
"distance_infer_center_oc_mv": draw_distance_infer_center_oc_mv,
|
| 466 |
+
"distance_infer_center_oo_mv": draw_distance_infer_center_oo_mv,
|
| 467 |
+
"spatial_imagination_oc_mv": draw_spatial_imagination_oc_mv,
|
| 468 |
+
"spatial_imagination_oo_mv": draw_spatial_imagination_oo_mv,
|
| 469 |
+
"spatial_imagination_map_mv": draw_spatial_imagination_map_mv,
|
| 470 |
+
"camera_motion_infer": draw_camera_motion_infer,
|
| 471 |
+
|
| 472 |
+
# Video
|
| 473 |
+
"distance_prediction_oo_video": draw_distance_prediction_oo_video,
|
| 474 |
+
"distance_infer_center_oo_video": draw_distance_infer_center_oo_video,
|
| 475 |
+
"spatial_imagination_oo_video": draw_spatial_imagination_oo_video,
|
| 476 |
+
"spatial_imagination_oc_video": draw_spatial_imagination_oc_video,
|
| 477 |
+
"spatial_imagination_oc_video_hard": draw_spatial_imagination_oc_video_hard,
|
| 478 |
+
"spatial_imagination_oo_video_hard": draw_spatial_imagination_oo_video_hard,
|
| 479 |
+
"obj_frame_locate": draw_obj_frame_locate,
|
| 480 |
+
"appearance_order": draw_appearance_order,
|
| 481 |
+
"room_size": draw_room_size,
|
| 482 |
+
"obj_count": draw_obj_count,
|
| 483 |
+
"nav": draw_nav,
|
| 484 |
+
}
|
spatial-model/VLM-3R/thinking-in-space/miscs/llava_result_check.md
ADDED
|
File without changes
|