File size: 23,151 Bytes
5316f3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | import argparse
import json
import math
import os
import random
import re
import sys
from pathlib import Path
from typing import Optional, Tuple
import torch
from PIL import Image
from transformers import AutoTokenizer
from internvl.conversation import get_conv_template
from internvl.conversation import register_conv_template
from internvl.conversation import Conversation
from internvl.conversation import SeparatorStyle
from internvl.model.internvl_chat import InternVLChatModel
from internvl.model.internvl_chat.configuration_internvl_chat import InternVLChatConfig
from internvl.train.dataset import build_transform, dynamic_preprocess
from evaluate_vqa import VQADataset, ds_collections
from textvqa_eval import TextVQAAccuracyEvaluator
BASE_PROMPT = "Answer the question using a single word or phrase."
VIZWIZ_PROMPT = "When the provided information is insufficient, respond with 'Unanswerable'. "
INFOGRAPHICSVQA_PROMPT = "Answer the question using a single word or phrase."
AI2D_PROMPT = ""
HIDDEN_REASONING_INSTRUCTION = (
"Think through the relevant visual evidence and any text in the image step by step internally before answering."
)
EXPLICIT_REASONING_INSTRUCTION = (
"Explain your reasoning step by step using the relevant visual evidence and any text in the image."
)
DEFAULT_FINAL_ANSWER_INSTRUCTION = "Provide the final answer only."
REPO_ROOT = Path(__file__).resolve().parents[2]
def ensure_internvl2_5_template() -> None:
try:
get_conv_template("internvl2_5")
return
except KeyError:
pass
register_conv_template(
Conversation(
name="internvl2_5",
system_template="<|im_start|>system\n{system_message}",
system_message="你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。",
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
sep_style=SeparatorStyle.MPT,
sep="<|im_end|>\n",
)
)
def configure_model(checkpoint_path: str) -> InternVLChatConfig:
config = InternVLChatConfig.from_json_file(os.path.join(checkpoint_path, "config.json"))
match = re.search(r"InternVL2-(\d+B)", checkpoint_path)
model_size = match.group(1) if match else checkpoint_path.split("-")[-1]
if model_size in ["1B", "40B"]:
config.llm_config._attn_implementation = "eager"
else:
config.llm_config.attn_implementation = "eager"
config.vision_config.use_flash_attn = True
return config
def split_model(num_layers: int, gpus_per_model: int) -> dict:
if gpus_per_model < 1:
raise ValueError("gpus_per_model must be >= 1")
device_map = {}
if gpus_per_model == 1:
for layer_idx in range(num_layers):
device_map[f"language_model.model.layers.{layer_idx}"] = 0
else:
# Keep the vision tower and embeddings on GPU 0 and spread decoder layers.
num_layers_per_gpu = math.ceil(num_layers / (gpus_per_model - 0.5))
num_layers_per_gpu = [num_layers_per_gpu] * gpus_per_model
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
layer_cnt = 0
for gpu_idx, layer_count in enumerate(num_layers_per_gpu):
for _ in range(layer_count):
if layer_cnt >= num_layers:
break
device_map[f"language_model.model.layers.{layer_cnt}"] = gpu_idx
layer_cnt += 1
if layer_cnt < num_layers:
for layer_idx in range(layer_cnt, num_layers):
device_map[f"language_model.model.layers.{layer_idx}"] = gpus_per_model - 1
device_map["vision_model"] = 0
device_map["mlp1"] = 0
device_map["language_model.model.tok_embeddings"] = 0
device_map["language_model.model.rotary_emb"] = 0
device_map["language_model.model.embed_tokens"] = 0
device_map["language_model.output"] = 0
device_map["language_model.model.norm"] = 0
device_map["language_model.lm_head"] = 0
if num_layers > 1 and gpus_per_model > 1:
device_map[f"language_model.model.layers.{num_layers - 1}"] = 1
return device_map
def load_model(checkpoint_path: str, config: InternVLChatConfig, args) -> InternVLChatModel:
ensure_internvl2_5_template()
kwargs = {"device_map": "auto"} if args.auto else {}
if args.gpus_per_model > 1 and not args.auto:
if args.gpus_per_model > torch.cuda.device_count():
raise ValueError(
f"gpus_per_model={args.gpus_per_model} exceeds visible CUDA devices={torch.cuda.device_count()}"
)
kwargs["device_map"] = split_model(config.llm_config.num_hidden_layers, args.gpus_per_model)
model = InternVLChatModel.from_pretrained(
checkpoint_path,
config=config,
low_cpu_mem_usage=True,
torch_dtype=torch.bfloat16,
load_in_8bit=args.load_in_8bit,
load_in_4bit=args.load_in_4bit,
**kwargs,
).eval()
if args.gpus_per_model == 1 and not args.auto and not args.load_in_8bit and not args.load_in_4bit:
model = model.cuda()
return model
def dataset_prompt(dataset_name: str) -> str:
if "vizwiz" in dataset_name:
return VIZWIZ_PROMPT + BASE_PROMPT
if "ai2d" in dataset_name:
return AI2D_PROMPT
if "infographicsvqa" in dataset_name:
return INFOGRAPHICSVQA_PROMPT
return BASE_PROMPT
def resolve_dataset_path(data_root: str, path: str) -> str:
if os.path.isabs(path):
return path
return os.path.join(data_root, path)
def resolve_image_path(image_path: str, data_root: str, jsonl_path: str = "") -> str:
candidates = []
if os.path.isabs(image_path):
candidates.append(image_path)
jsonl_dir = os.path.dirname(jsonl_path) if jsonl_path else ""
candidates.append(os.path.join(data_root, image_path))
if image_path.startswith("data/"):
candidates.append(os.path.join(data_root, image_path[len("data/"):]))
if jsonl_dir:
candidates.append(os.path.join(jsonl_dir, image_path))
candidates.append(os.path.join(jsonl_dir, os.path.basename(image_path)))
for candidate in candidates:
if candidate and os.path.exists(candidate):
return candidate
raise FileNotFoundError(f"Could not resolve image path: {image_path}")
def load_textvqa_sample(jsonl_path: str, sample_index: int) -> Tuple[str, str, Optional[int], Optional[str]]:
with open(jsonl_path) as f:
for idx, line in enumerate(f):
if idx == sample_index:
item = json.loads(line)
return item["image"], item["question"], item.get("question_id"), item.get("answer")
raise IndexError(f"sample_index {sample_index} is out of range for {jsonl_path}")
def build_pixel_values(
image_path: str,
image_size: int,
dynamic: bool,
use_thumbnail: bool,
max_num: int,
) -> torch.Tensor:
transform = build_transform(is_train=False, input_size=image_size)
image = Image.open(image_path).convert("RGB")
if dynamic:
images = dynamic_preprocess(
image,
image_size=image_size,
use_thumbnail=use_thumbnail,
max_num=max_num,
)
else:
images = [image]
return torch.stack([transform(img) for img in images])
def build_query(model: InternVLChatModel, tokenizer, question: str, num_patches: int):
img_context_token = "<IMG_CONTEXT>"
img_start_token = "<img>"
img_end_token = "</img>"
if "<image>" not in question:
question = "<image>\n" + question
model.img_context_token_id = tokenizer.convert_tokens_to_ids(img_context_token)
template = get_conv_template(model.template)
template.system_message = model.system_message
template.append_message(template.roles[0], question)
template.append_message(template.roles[1], None)
query = template.get_prompt()
image_tokens = img_start_token + img_context_token * model.num_image_token * num_patches + img_end_token
query = query.replace("<image>", image_tokens, 1)
return query, template
def model_input_device(model: InternVLChatModel) -> torch.device:
return next(model.vision_model.parameters()).device
@torch.inference_mode()
def generate_answer(
model: InternVLChatModel,
tokenizer,
pixel_values: torch.Tensor,
question: str,
generation_config: dict,
) -> str:
query, template = build_query(model, tokenizer, question, pixel_values.shape[0])
model_inputs = tokenizer(query, return_tensors="pt")
device = model_input_device(model)
input_ids = model_inputs["input_ids"].to(device)
attention_mask = model_inputs["attention_mask"].to(device)
eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
output_ids = model.generate(
pixel_values=pixel_values.to(device=device, dtype=torch.bfloat16),
input_ids=input_ids,
attention_mask=attention_mask,
large_model=True,
eos_token_id=eos_token_id,
**generation_config,
)
response = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
return response.split(template.sep)[0].strip()
def build_eval_entries(result_items, annotation_file: str):
evaluator = TextVQAAccuracyEvaluator()
with open(annotation_file) as f:
annotations = json.load(f)["annotations"]
question_id_to_answers = {
item["question_id"]: [answer["answer"] for answer in item["answers"]]
for item in annotations
}
eval_entries = [
{
"question_id": item["question_id"],
"answer": item["answer"],
"pred_answer": item["answer"],
"gt_answers": question_id_to_answers[item["question_id"]],
}
for item in result_items
]
return evaluator, eval_entries
def make_generation_config(num_beams: int, max_new_tokens: int, temperature: float) -> dict:
generation_config = {
"num_beams": num_beams,
"max_new_tokens": max_new_tokens,
"min_new_tokens": 1,
"do_sample": temperature > 0,
}
if temperature > 0:
generation_config["temperature"] = temperature
return generation_config
def append_instruction(question: str, instruction: str) -> str:
instruction = instruction.strip()
if not instruction:
return question
return f"{question.rstrip()}\n{instruction}"
def render_custom_prompt(question: str, prompt_template: str) -> str:
prompt_template = prompt_template.strip()
if not prompt_template:
raise ValueError("custom_prompt_template must be non-empty when reasoning_mode='custom_prompt'.")
if "{question}" in prompt_template:
return prompt_template.replace("{question}", question)
if "Question:" in prompt_template or "Question:" in prompt_template:
return f"{prompt_template.rstrip()} {question}"
return f"{prompt_template.rstrip()}\nQuestion: {question}"
def extract_final_answer(response: str, final_answer_prefix: str) -> str:
final_answer_prefix = final_answer_prefix.strip()
if not final_answer_prefix:
return response.strip()
pattern = re.compile(rf"(?im)^{re.escape(final_answer_prefix)}\s*(.*)$")
match = pattern.search(response)
if not match:
return response.strip()
inline_answer = match.group(1).strip()
if inline_answer:
return inline_answer
trailing_lines = response[match.end():].splitlines()
for line in trailing_lines:
stripped = line.strip()
if stripped:
return stripped
return ""
def make_reasoning_generation_config(base_generation_config: dict, args) -> dict:
generation_config = dict(base_generation_config)
generation_config["max_new_tokens"] = args.reasoning_max_new_tokens
temperature = args.reasoning_temperature
generation_config["do_sample"] = temperature > 0
if temperature > 0:
generation_config["temperature"] = temperature
else:
generation_config.pop("temperature", None)
return generation_config
def generate_answer_with_reasoning(
model: InternVLChatModel,
tokenizer,
pixel_values: torch.Tensor,
question: str,
generation_config: dict,
reasoning_mode: str,
reasoning_generation_config: Optional[dict] = None,
final_answer_instruction: str = "",
) -> Tuple[str, Optional[str]]:
if reasoning_mode == "none":
return generate_answer(model, tokenizer, pixel_values, question, generation_config), None
if reasoning_mode == "prompt":
prompted_question = append_instruction(question, HIDDEN_REASONING_INSTRUCTION)
return generate_answer(model, tokenizer, pixel_values, prompted_question, generation_config), None
if reasoning_generation_config is None:
raise ValueError("reasoning_generation_config is required when reasoning_mode='two_pass'.")
reasoning_question = append_instruction(question, EXPLICIT_REASONING_INSTRUCTION)
reasoning = generate_answer(model, tokenizer, pixel_values, reasoning_question, reasoning_generation_config)
final_instruction = final_answer_instruction or DEFAULT_FINAL_ANSWER_INSTRUCTION
final_question = append_instruction(
question,
f"Reasoning:\n{reasoning}\n{final_instruction}",
)
answer = generate_answer(model, tokenizer, pixel_values, final_question, generation_config)
return answer, reasoning
def run_single(args):
tokenizer = AutoTokenizer.from_pretrained(
args.checkpoint,
trust_remote_code=True,
use_fast=False,
)
config = configure_model(args.checkpoint)
model = load_model(args.checkpoint, config, args)
if args.textvqa_jsonl:
image_path, prompt, question_id, answer = load_textvqa_sample(args.textvqa_jsonl, args.sample_index)
image_path = resolve_image_path(image_path, args.data_root, args.textvqa_jsonl)
else:
image_path = args.image_path
prompt = args.prompt
question_id = None
answer = None
if not image_path or not prompt:
raise ValueError("Provide either --image-path and --prompt, or --textvqa-jsonl.")
if not os.path.exists(image_path):
raise FileNotFoundError(f"image not found: {image_path}")
image_size = config.force_image_size or config.vision_config.image_size
pixel_values = build_pixel_values(
image_path=image_path,
image_size=image_size,
dynamic=args.dynamic,
use_thumbnail=config.use_thumbnail,
max_num=args.max_num,
)
generation_config = make_generation_config(
num_beams=args.num_beams,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
)
reasoning_generation_config = None
if args.reasoning_mode == "two_pass":
reasoning_generation_config = make_reasoning_generation_config(generation_config, args)
raw_prediction = None
if args.reasoning_mode == "custom_prompt":
raw_prediction = generate_answer(
model,
tokenizer,
pixel_values,
render_custom_prompt(prompt, args.custom_prompt_template),
generation_config,
)
prediction = (
extract_final_answer(raw_prediction, args.final_answer_prefix)
if args.extract_final_answer
else raw_prediction
)
reasoning = None
else:
prediction, reasoning = generate_answer_with_reasoning(
model=model,
tokenizer=tokenizer,
pixel_values=pixel_values,
question=prompt,
generation_config=generation_config,
reasoning_mode=args.reasoning_mode,
reasoning_generation_config=reasoning_generation_config,
final_answer_instruction=args.answer_format_prompt,
)
print(f"checkpoint: {args.checkpoint}")
print(f"image_path: {image_path}")
if question_id is not None:
print(f"question_id: {question_id}")
if answer is not None:
print(f"reference_answer: {answer}")
print(f"prompt: {prompt}")
if reasoning is not None:
print(f"reasoning: {reasoning}")
if raw_prediction is not None:
print(f"raw_prediction: {raw_prediction}")
print(f"prediction: {prediction}")
def run_textvqa_eval(args):
if args.dataset not in ds_collections:
raise KeyError(f"unknown dataset: {args.dataset}")
ds_cfg = ds_collections[args.dataset]
test_file = args.test_file or resolve_dataset_path(args.data_root, ds_cfg["test"])
train_file = args.train_file or resolve_dataset_path(args.data_root, ds_cfg["train"])
annotation_file = args.annotation_file or resolve_dataset_path(args.data_root, ds_cfg["annotation"])
tokenizer = AutoTokenizer.from_pretrained(
args.checkpoint,
trust_remote_code=True,
use_fast=False,
)
config = configure_model(args.checkpoint)
model = load_model(args.checkpoint, config, args)
image_size = config.force_image_size or config.vision_config.image_size
prompt = args.prompt or dataset_prompt(args.dataset)
dataset = VQADataset(
train=train_file,
test=test_file,
prompt=prompt,
few_shot=0,
input_size=image_size,
dynamic_image_size=args.dynamic,
use_thumbnail=config.use_thumbnail,
max_num=args.max_num,
)
num_items = len(dataset) if args.limit is None else min(len(dataset), args.limit)
result_items = []
generation_config = make_generation_config(
num_beams=args.num_beams,
max_new_tokens=args.max_new_tokens or ds_cfg["max_new_tokens"],
temperature=args.temperature,
)
reasoning_generation_config = None
if args.reasoning_mode == "two_pass":
reasoning_generation_config = make_reasoning_generation_config(generation_config, args)
for idx in range(num_items):
sample = dataset[idx]
raw_prediction = None
if args.reasoning_mode == "custom_prompt":
raw_prediction = generate_answer(
model,
tokenizer,
sample["pixel_values"],
render_custom_prompt(sample["question"], args.custom_prompt_template),
generation_config,
)
prediction = (
extract_final_answer(raw_prediction, args.final_answer_prefix)
if args.extract_final_answer
else raw_prediction
)
reasoning = None
else:
prediction, reasoning = generate_answer_with_reasoning(
model=model,
tokenizer=tokenizer,
pixel_values=sample["pixel_values"],
question=sample["question"],
generation_config=generation_config,
reasoning_mode=args.reasoning_mode,
reasoning_generation_config=reasoning_generation_config,
)
result_item = {
"question": sample["question"],
"question_id": sample["question_id"],
"answer": prediction,
"annotation": sample["annotation"],
}
if raw_prediction is not None:
result_item["raw_answer"] = raw_prediction
if args.save_reasoning and reasoning is not None:
result_item["reasoning"] = reasoning
result_items.append(result_item)
if (idx + 1) % args.log_every == 0 or idx + 1 == num_items:
print(f"[{idx + 1}/{num_items}] question_id={sample['question_id']} prediction={prediction}")
sys.stdout.flush()
os.makedirs(args.out_dir, exist_ok=True)
run_name = args.run_name or f"{args.dataset}_{os.path.basename(args.checkpoint)}"
output_file = os.path.join(args.out_dir, f"{run_name}.json")
with open(output_file, "w") as f:
json.dump(result_items, f, ensure_ascii=False, indent=2)
evaluator, eval_entries = build_eval_entries(result_items, annotation_file)
accuracy = evaluator.eval_pred_list(eval_entries)
print(f"dataset: {args.dataset}")
print(f"checkpoint: {args.checkpoint}")
print(f"count: {num_items}")
print(f"accuracy: {accuracy:.6f}")
print(f"results_file: {output_file}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", type=str, required=True)
parser.add_argument("--mode", type=str, choices=["single", "textvqa_eval"], default="single")
parser.add_argument("--image-path", type=str, default="")
parser.add_argument("--prompt", type=str, default="")
parser.add_argument("--textvqa-jsonl", type=str, default="")
parser.add_argument("--sample-index", type=int, default=0)
parser.add_argument("--dataset", type=str, default="textvqa_val")
parser.add_argument("--data-root", type=str, default=str(REPO_ROOT))
parser.add_argument("--test-file", type=str, default="")
parser.add_argument("--train-file", type=str, default="")
parser.add_argument("--annotation-file", type=str, default="")
parser.add_argument("--out-dir", type=str, default=str(REPO_ROOT / "outputs" / "native_single"))
parser.add_argument("--run-name", type=str, default="")
parser.add_argument("--limit", type=int, default=None)
parser.add_argument("--max-new-tokens", type=int, default=0)
parser.add_argument("--num-beams", type=int, default=1)
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--reasoning-mode", type=str, choices=["none", "prompt", "two_pass", "custom_prompt"], default="none")
parser.add_argument("--reasoning-max-new-tokens", type=int, default=64)
parser.add_argument("--reasoning-temperature", type=float, default=0.0)
parser.add_argument("--save-reasoning", action="store_true")
parser.add_argument("--answer-format-prompt", type=str, default="")
parser.add_argument("--custom-prompt-template", type=str, default="")
parser.add_argument("--extract-final-answer", action="store_true")
parser.add_argument("--final-answer-prefix", type=str, default="Final answer:")
parser.add_argument("--dynamic", action="store_true")
parser.add_argument("--max-num", type=int, default=6)
parser.add_argument("--log-every", type=int, default=20)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--gpus-per-model", type=int, default=1)
parser.add_argument("--auto", action="store_true")
parser.add_argument("--load-in-8bit", action="store_true")
parser.add_argument("--load-in-4bit", action="store_true")
args = parser.parse_args()
if not torch.cuda.is_available():
raise RuntimeError("CUDA is required for native InternVL inference.")
random.seed(args.seed)
torch.manual_seed(args.seed)
if args.mode == "single":
if args.max_new_tokens == 0:
args.max_new_tokens = 32
run_single(args)
return
if args.max_new_tokens == 0:
args.max_new_tokens = None
run_textvqa_eval(args)
if __name__ == "__main__":
main()
|