| 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: |
| |
| 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() |
|
|