diff --git a/VLMEvalKit-sudoku/llava/__pycache__/constants.cpython-310.pyc b/VLMEvalKit-sudoku/llava/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af8f679665ab3cefe53a5d4aeb7c8f458e08836c Binary files /dev/null and b/VLMEvalKit-sudoku/llava/__pycache__/constants.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/llava/eval/eval_ai2d.py b/VLMEvalKit-sudoku/llava/eval/eval_ai2d.py new file mode 100644 index 0000000000000000000000000000000000000000..236d61835c4077a4ea2dad93aeed5010a1ecbec7 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/eval/eval_ai2d.py @@ -0,0 +1,76 @@ +import os +import argparse +import json +import re +import sys +print(sys.path) + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument('--annotation-file', type=str) + parser.add_argument('--result-file', type=str) + parser.add_argument('--result-dir', type=str) + parser.add_argument('--mid_result', type=str) + parser.add_argument('--output_result', type=str) + return parser.parse_args() + + +def evaluate_exact_match_accuracy(entries): + scores = [] + for elem in entries: + if isinstance(elem['annotation'], str): + elem['annotation'] = [elem['annotation']] + score = max([ + (1.0 if + (elem['answer'].strip().lower() == ann.strip().lower()) else 0.0) + for ann in elem['annotation'] + ]) + scores.append(score) + return sum(scores) / len(scores) + + +def eval_single(annotation_file, result_file): + experiment_name = os.path.splitext(os.path.basename(result_file))[0] + print(experiment_name) + # annotations = json.load(open(annotation_file))['data'] + annotations = [ + json.loads(q) for q in open(os.path.expanduser(annotation_file), "r") + ] + annotations = {(annotation['question_id'], annotation['question'].lower()): annotation for annotation in annotations} + results = [json.loads(line) for line in open(result_file)] + + pred_list = [] + mid_list = [] + for result in results: + annotation = annotations[(result['question_id'], result['prompt'].lower())] + pred_list.append({ + "answer": result['text'], + "annotation": annotation['answer'], + }) + mid_list.append(result) + mid_list[-1]["annotation"] = annotation['answer'] + + acc = evaluate_exact_match_accuracy(pred_list) + acc = 100. * acc + print('Samples: {}\nAccuracy: {:.2f}%\n'.format(len(pred_list), acc)) + return len(pred_list), acc, mid_list + + +if __name__ == "__main__": + args = get_args() + + if args.result_file is not None: + samples, acc, mid_result = eval_single(args.annotation_file, args.result_file) + + if args.result_dir is not None: + for result_file in sorted(os.listdir(args.result_dir)): + if not result_file.endswith('.jsonl'): + print(f'Skipping {result_file}') + continue + samples, acc, mid_result = eval_single(args.annotation_file, os.path.join(args.result_dir, result_file)) + + with open(args.mid_result, 'w') as f: + json.dump(mid_result, f, indent=2) + + with open(args.output_result, 'w') as f: + json.dump({'samples': samples, 'acc': acc}, f, indent=2) diff --git a/VLMEvalKit-sudoku/llava/eval/eval_rec.py b/VLMEvalKit-sudoku/llava/eval/eval_rec.py new file mode 100644 index 0000000000000000000000000000000000000000..6744f5f6148c6c9aa9586a0ccae514499c9103a8 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/eval/eval_rec.py @@ -0,0 +1,171 @@ +import os +import json +import argparse +import torch +from torchvision.ops import box_iou +import sys +import logging +import warnings +from typing import Dict, Any, Sequence +from PIL import Image +from tqdm import tqdm + +def expand2square(pil_img, background_color): + width, height = pil_img.size + if width == height: + return pil_img + elif width > height: + result = Image.new(pil_img.mode, (width, width), background_color) + result.paste(pil_img, (0, (width - height) // 2)) + return result + else: + result = Image.new(pil_img.mode, (height, height), background_color) + result.paste(pil_img, ((height - width) // 2, 0)) + return result + + +def eval_rec(answers, labels): + preds = [] + targets = [] + # for answer, annotation in tqdm(zip(answers, labels)): + for answer, annotation in zip(answers, labels): + text = answer['text'] + label = annotation['label'] + + #"text": "[0.09, 0.29, 0.37, 0.98]\n\nThe woman is wearing black pants." + # remove suffix :"\n\nThe woman is wearing black pants." of text, and prserve "[0.09, 0.29, 0.37, 0.98]" + text = text.split('\n\n')[0] + + # remove [] + text = text.replace('[', '') + text = text.replace(']', '') + label = label.replace('[', '') + label = label.replace(']', '') + # crop the coord + coords = text.strip(' ').split(',') + try: + xmin, ymin, xmax, ymax = coords + except: + continue + pred = torch.as_tensor([float(xmin), float(ymin), + float(xmax), float(ymax)]) + preds.append(pred) + + coords = label.strip(' ').split(',') + xmin, ymin, xmax, ymax = coords + target = torch.as_tensor([float(xmin), float(ymin), + float(xmax), float(ymax)]) + + img = Image.open('./playground/data/eval/rec/images/train2017/' + annotation['image']) + + width_ori, height_ori = img.size + xmin, ymin, xmax, ymax = target + # print(annotation['text'].split(':')[-1], xmin, ymin, xmax, ymax) + xmin, ymin, xmax, ymax = xmin * width_ori, ymin * height_ori, xmax * width_ori, ymax * height_ori + + # import matplotlib.pyplot as plt + # plt.figure(annotation['text'].split(':')[-1]) + # plt.axis('off') + # plt.imshow(img) + # plt.gca().add_patch( + # plt.Rectangle( + # (xmin, ymin), xmax - xmin, ymax - ymin, color='red', fill=False + # ) + # ) + # plt.savefig('image1.png') + if 0: + if width_ori > height_ori: + ymin += (width_ori - height_ori) // 2 + ymax += (width_ori - height_ori) // 2 + width = width_ori + height = height_ori + width_ori - height_ori + else: + xmin += (height_ori - width_ori) // 2 + xmax += (height_ori - width_ori) // 2 + width = width_ori + height_ori - width_ori + height = height_ori + else: + width = width_ori + height = height_ori + + # import matplotlib.pyplot as plt + # plt.figure(annotation['text'] + '1'.split(':')[-1]) + # plt.axis('off') + + # img_pad = expand2square(img, (0,0,0)) + # plt.imshow(img_pad) + # plt.gca().add_patch( + # plt.Rectangle( + # (xmin, ymin), xmax - xmin, ymax - ymin, color='red', fill=False + # ) + # ) + # plt.savefig('image2.png') + # import pdb; pdb.set_trace() + + target = torch.as_tensor([float(xmin / width), float(ymin / height), + float(xmax / width), float(ymax / height)]) + targets.append(target) + + pred_boxes = torch.stack(preds, dim=0) + target_boxes = torch.stack(targets, dim=0) + + # normalized box value is too small, so that the area is 0. + ious = box_iou(pred_boxes * 1000, target_boxes * 1000) + ious = torch.einsum('i i -> i', ious) # take diag elem + # NOTE: please note iou only calculate for success target + iou = ious.mean().item() + correct = (ious > 0.5).sum().item() + # HACK: currently we expand image to square. so this iou is the real iou. + warn_message = "this iou is calculate on normalized box. just for non-rigorous training progress checking." \ + "the value is consistent with real iou only if image.width == image.height." + warnings.warn(warn_message) + + return { + 'accuracy': 1.0 * correct / len(targets), + 'iou': iou, + 'warning': warn_message, + } + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--annotation-file", type=str) + parser.add_argument("--question-file", type=str) + parser.add_argument("--result-file", type=str) + args = parser.parse_args() + + questions = [json.loads(line) for line in open(args.question_file)] + questions = {question['question_id']: question for question in questions} + answers = [json.loads(q) for q in open(args.result_file)] + annotations = [json.loads(a) for a in open(args.annotation_file)] + + val_splits = ['REC_refcoco_unc_val', + 'REC_refcoco_unc_testA', + 'REC_refcoco_unc_testB', + 'REC_refcoco+_unc_val', + 'REC_refcoco+_unc_testA', + 'REC_refcoco+_unc_testB', + 'REC_refcocog_umd_val', + 'REC_refcocog_umd_test',] + + # val_splits = ['REC_refcoco+_unc_val'] + + for category in val_splits: + cur_answers = [x for x in answers if questions[x['question_id']]['category'] == category] + cur_labels = [x for x in annotations if questions[x['question_id']]['category'] == category] + if len(cur_answers) == 0: + continue + print('split: {}, # samples answer: {}, # samples target {}'.format(category, len(cur_answers), len(cur_labels))) + # align the targe and label + align_answers = [] + align_labels = [] + for cur_answer in cur_answers: + for cur_label in cur_labels: + if cur_answer['question_id'] == cur_label['question_id']: + align_answers.append(cur_answer) + align_labels.append(cur_label) + break + # eval_info = eval_rec(cur_answers, cur_labels) + eval_info = eval_rec(align_answers, align_labels) + print("=================={}==================".format(category)) + print(eval_info) + print("======================================") diff --git a/VLMEvalKit-sudoku/llava/eval/generate_webpage_data_from_table.py b/VLMEvalKit-sudoku/llava/eval/generate_webpage_data_from_table.py new file mode 100644 index 0000000000000000000000000000000000000000..92602258ccd953a1d7137056aaf15c8de8166e21 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/eval/generate_webpage_data_from_table.py @@ -0,0 +1,111 @@ +"""Generate json file for webpage.""" +import json +import os +import re + +# models = ['llama', 'alpaca', 'gpt35', 'bard'] +models = ['vicuna'] + + +def read_jsonl(path: str, key: str=None): + data = [] + with open(os.path.expanduser(path)) as f: + for line in f: + if not line: + continue + data.append(json.loads(line)) + if key is not None: + data.sort(key=lambda x: x[key]) + data = {item[key]: item for item in data} + return data + + +def trim_hanging_lines(s: str, n: int) -> str: + s = s.strip() + for _ in range(n): + s = s.split('\n', 1)[1].strip() + return s + + +if __name__ == '__main__': + questions = read_jsonl('table/question.jsonl', key='question_id') + + # alpaca_answers = read_jsonl('table/answer/answer_alpaca-13b.jsonl', key='question_id') + # bard_answers = read_jsonl('table/answer/answer_bard.jsonl', key='question_id') + # gpt35_answers = read_jsonl('table/answer/answer_gpt35.jsonl', key='question_id') + # llama_answers = read_jsonl('table/answer/answer_llama-13b.jsonl', key='question_id') + vicuna_answers = read_jsonl('table/answer/answer_vicuna-13b.jsonl', key='question_id') + ours_answers = read_jsonl('table/results/llama-13b-hf-alpaca.jsonl', key='question_id') + + review_vicuna = read_jsonl('table/review/review_vicuna-13b_llama-13b-hf-alpaca.jsonl', key='question_id') + # review_alpaca = read_jsonl('table/review/review_alpaca-13b_vicuna-13b.jsonl', key='question_id') + # review_bard = read_jsonl('table/review/review_bard_vicuna-13b.jsonl', key='question_id') + # review_gpt35 = read_jsonl('table/review/review_gpt35_vicuna-13b.jsonl', key='question_id') + # review_llama = read_jsonl('table/review/review_llama-13b_vicuna-13b.jsonl', key='question_id') + + records = [] + for qid in questions.keys(): + r = { + 'id': qid, + 'category': questions[qid]['category'], + 'question': questions[qid]['text'], + 'answers': { + # 'alpaca': alpaca_answers[qid]['text'], + # 'llama': llama_answers[qid]['text'], + # 'bard': bard_answers[qid]['text'], + # 'gpt35': gpt35_answers[qid]['text'], + 'vicuna': vicuna_answers[qid]['text'], + 'ours': ours_answers[qid]['text'], + }, + 'evaluations': { + # 'alpaca': review_alpaca[qid]['text'], + # 'llama': review_llama[qid]['text'], + # 'bard': review_bard[qid]['text'], + 'vicuna': review_vicuna[qid]['content'], + # 'gpt35': review_gpt35[qid]['text'], + }, + 'scores': { + 'vicuna': review_vicuna[qid]['tuple'], + # 'alpaca': review_alpaca[qid]['score'], + # 'llama': review_llama[qid]['score'], + # 'bard': review_bard[qid]['score'], + # 'gpt35': review_gpt35[qid]['score'], + }, + } + + # cleanup data + cleaned_evals = {} + for k, v in r['evaluations'].items(): + v = v.strip() + lines = v.split('\n') + # trim the first line if it's a pair of numbers + if re.match(r'\d+[, ]+\d+', lines[0]): + lines = lines[1:] + v = '\n'.join(lines) + cleaned_evals[k] = v.replace('Assistant 1', "**Assistant 1**").replace('Assistant 2', '**Assistant 2**') + + r['evaluations'] = cleaned_evals + records.append(r) + + # Reorder the records, this is optional + for r in records: + if r['id'] <= 20: + r['id'] += 60 + else: + r['id'] -= 20 + for r in records: + if r['id'] <= 50: + r['id'] += 10 + elif 50 < r['id'] <= 60: + r['id'] -= 50 + for r in records: + if r['id'] == 7: + r['id'] = 1 + elif r['id'] < 7: + r['id'] += 1 + + records.sort(key=lambda x: x['id']) + + # Write to file + with open('webpage/data.json', 'w') as f: + json.dump({'questions': records, 'models': models}, f, indent=2) diff --git a/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_llama.cpython-310.pyc b/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_llama.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6e07adcab93774269c8cf5877a33d95b20cc935 Binary files /dev/null and b/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_llama.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_qwen3.cpython-310.pyc b/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_qwen3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eb79a91440aef5017f5bc7f5fb2cf8034bdd50a Binary files /dev/null and b/VLMEvalKit-sudoku/llava/model/language_model/__pycache__/llava_qwen3.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/llava/model/language_model/llava_qwen.py b/VLMEvalKit-sudoku/llava/model/language_model/llava_qwen.py new file mode 100644 index 0000000000000000000000000000000000000000..708b20fcfa05deb7e34451ae150bd5e7d065db67 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/model/language_model/llava_qwen.py @@ -0,0 +1,165 @@ +# Copyright 2024 Hao Zhang +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from typing import List, Optional, Tuple, Union, Dict +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +import transformers +from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +# from ...constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM +from transformers import Qwen2Config, Qwen2Model, Qwen2ForCausalLM + +# from .qwen.modeling_qwen import QWenLMHeadModel, QWenModel +# from .qwen.configuration_qwen import QWenConfig + + +class LlavaQwenConfig(Qwen2Config): + model_type = "llava_qwen" + + +class LlavaQwenModel(LlavaMetaModel, Qwen2Model): + config_class = LlavaQwenConfig + + def __init__(self, config: Qwen2Config): + super(LlavaQwenModel, self).__init__(config) + + +class LlavaQwenForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaQwenConfig + + def __init__(self, config): + # super(Qwen2ForCausalLM, self).__init__(config) + Qwen2ForCausalLM.__init__(self, config) + config.model_type = "llava_qwen" + config.rope_scaling = None + + self.model = LlavaQwenModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + modalities: Optional[List[str]] = ["image"], + dpo_forward: Optional[bool] = False, + cache_position=None, + patch_images: Optional[torch.FloatTensor] = None, + ind_tokens: Optional[List[int]] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes,patch_images=patch_images, + ind_tokens=ind_tokens) + + if dpo_forward: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + return logits, labels + + else: + output = super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + # import pdb; pdb.set_trace() + # output_id = torch.softmax(output[1], dim=2) + # output_id = torch.argmax(output_id, dim=2) + return output + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + modalities: Optional[List[str]] = ["image"], + patch_images: Optional[torch.FloatTensor] = None, + ind_tokens: Optional[List[int]] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes, patch_images=patch_images, + ind_tokens=ind_tokens) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + patch_images = kwargs.pop("patch_images", None) + ind_tokens = kwargs.pop("ind_tokens", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + if patch_images is not None: + inputs['patch_images'] = patch_images + if ind_tokens is not None: + inputs['ind_tokens'] = ind_tokens + return inputs + + +AutoConfig.register("llava_qwen", LlavaQwenConfig) +AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwenForCausalLM) diff --git a/VLMEvalKit-sudoku/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..aad2058003962a4ab286bf4e1ae956288af34e62 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA01-CLIP-B-16.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16, + "eva_model_name": "eva-clip-b-16", + "ls_init_value": 0.1, + "drop_path_rate": 0.0 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/VLMEvalKit-sudoku/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..03b22ad3cfb92f9c843b9ec8d672e57e7a9ba4a2 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json @@ -0,0 +1,29 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "drop_path_rate": 0, + "head_width": 64, + "mlp_ratio": 2.6667, + "patch_size": 14, + "eva_model_name": "eva-clip-l-14", + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git a/VLMEvalKit-sudoku/llava/model/multimodal_encoder/modeling_qwen2_5vl.py b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/modeling_qwen2_5vl.py new file mode 100644 index 0000000000000000000000000000000000000000..7244bac56761096bd5f923d627515cb40cae68c3 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/model/multimodal_encoder/modeling_qwen2_5vl.py @@ -0,0 +1,207 @@ +from transformers import PretrainedConfig +from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionTransformerPretrainedModel + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from PIL import Image +from functools import partial, reduce +from typing import Any, Optional, Tuple, Union, Dict +from transformers.image_processing_utils import BatchFeature, get_size_dict +from transformers.image_transforms import ( + convert_to_rgb, + normalize, + rescale, + resize, + to_channel_dimension_format, +) +from transformers.image_utils import ( + ChannelDimension, + PILImageResampling, + to_numpy_array, +) + +class QwenVisionConfig(PretrainedConfig): + model_type = "qwen2_5_vl" + base_config_key = "vision_config" + + def __init__( + self, + depth=32, + hidden_size=3584, + hidden_act="silu", + intermediate_size=3420, + num_heads=16, + in_channels=3, + patch_size=14, + spatial_merge_size=2, + temporal_patch_size=2, + tokens_per_second=4, + window_size=112, + out_hidden_size=3584, + fullatt_block_indexes=[7, 15, 23, 31], + initializer_range=0.02, + **kwargs, + ): + super().__init__(**kwargs) + + self.depth = depth + self.hidden_size = hidden_size + self.hidden_act = hidden_act + self.intermediate_size = intermediate_size + self.num_heads = num_heads + self.in_channels = in_channels + self.patch_size = patch_size + self.spatial_merge_size = spatial_merge_size + self.temporal_patch_size = temporal_patch_size + self.tokens_per_second = tokens_per_second + self.window_size = window_size + self.fullatt_block_indexes = fullatt_block_indexes + self.out_hidden_size = out_hidden_size + self.initializer_range = initializer_range + +class QwenImageProcessor: + def __init__(self, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), size=(392, 392), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST): + crop_size = crop_size if crop_size is not None else {"height": 392, "width": 392} + crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size") + + self.image_mean = image_mean + self.image_std = image_std + self.size = size + self.resample = resample + self.rescale_factor = rescale_factor + self.data_format = data_format + self.crop_size = crop_size + + def preprocess(self, images, do_resize = True, do_center_crop = True, do_rescale = True, do_normalize = True, return_tensors = 'pt'): + if isinstance(images, Image.Image): + images = [images] + else: + # to adapt video data + images = [to_numpy_array(image) for image in images] + assert isinstance(images, list) + + # do_resize=False, do_center_crop=False, do_rescale=True, do_normalize=True, + + transforms = [ + convert_to_rgb, + to_numpy_array + ] + + if do_resize: + transforms.append(partial(resize, size=self.size, resample=self.resample, data_format=self.data_format)) + if do_rescale: + transforms.append(partial(rescale, scale=self.rescale_factor, data_format=self.data_format)) + if do_normalize: + transforms.append(partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format)) + + transforms.append(partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format)) + + images = reduce(lambda x, f: [*map(f, x)], transforms, images) + data = {"pixel_values": images} + return BatchFeature(data=data, tensor_type=return_tensors) + +class Qwen2_5VLVisionTower(nn.Module): + def __init__(self, vision_tower, vision_tower_cfg, delay_load=False): + super().__init__() + + self.is_loaded = False + + self.config = QwenVisionConfig() ### 需要定义 + + self.vision_tower_name = vision_tower + + self.image_processor = QwenImageProcessor() + + if not delay_load: + print(f"Loading vision tower: {vision_tower}") + self.load_model() + + elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False): + print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.") + self.load_model() + + elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts: + print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.") + self.load_model() + + else: + self.cfg_only = self.config + + def load_model(self, device_map=None): + if self.is_loaded: + print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name)) + return + + self.vision_tower = Qwen2_5_VisionTransformerPretrainedModel.from_pretrained(self.vision_tower_name, device_map=device_map) + print('qwen2_5vl vision tower loaded') + self.vision_tower.requires_grad_(False) + self.is_loaded = True + + def forward(self, images, patch_sizes=None): + if type(images) is list: + pixel_values = [] + vision_grid_thws = [] + spatial_patch_size = self.vision_tower.config.spatial_patch_size + temporal_patch_size = self.vision_tower.config.temporal_patch_size + spatial_merge_size = 2 + data = {} + for image in images: + image = image.to(device=self.device, dtype=self.dtype).unsqueeze(0) + image = torch.cat([image, image], dim=0) ### t, c, h, w + grid_t = image.shape[0] // temporal_patch_size + grid_h, grid_w = image.shape[2] // spatial_patch_size, image.shape[3] // spatial_patch_size + channel = image.shape[1] + patches = image.reshape(grid_t, temporal_patch_size, channel, + grid_h // spatial_merge_size, spatial_merge_size, spatial_patch_size, + grid_w // spatial_merge_size, spatial_merge_size, spatial_patch_size) + patches = patches.permute(0, 3, 6, 4, 7, 2, 1, 5, 8) + flatten_patches = patches.reshape( + grid_t * grid_h * grid_w, + channel * temporal_patch_size * spatial_patch_size * spatial_patch_size + ) + + pixel_values.extend(flatten_patches) + vision_grid_thws.append(torch.tensor([grid_t, grid_h, grid_w]).unsqueeze(0)) + pixel_values = torch.stack(pixel_values, dim=0) + pixel_values = pixel_values.to(device=self.device, dtype=self.dtype) + vision_grid_thws = torch.cat(vision_grid_thws, dim=0).to(device=self.device) + image_embeds = self.vision_tower(pixel_values, grid_thw=vision_grid_thws) + split_sizes = (vision_grid_thws.prod(-1) // spatial_merge_size**2).tolist() + image_features = torch.split(image_embeds, split_sizes) + else: + print('no support for parallel processing') + exit() + return image_features + + @property + def dummy_feature(self): + return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype) + + @property + def dtype(self): + for p in self.vision_tower.parameters(): + return p.dtype + + @property + def device(self): + for p in self.vision_tower.parameters(): + return p.device + + @property + def hidden_size(self): + return self.config.hidden_size + + @property + def num_patches(self): + return (self.config.image_size // self.config.patch_size) ** 2 + + @property + def num_patches_per_side(self): + return self.config.image_size // self.config.patch_size + # return self.model_config["vision_cfg"]["image_size"] // self.model_config["vision_cfg"]["patch_size"] + + @property + def image_size(self): + return self.config.image_size \ No newline at end of file diff --git a/VLMEvalKit-sudoku/llava/model/multimodal_resampler/__pycache__/masked_drop.cpython-310.pyc b/VLMEvalKit-sudoku/llava/model/multimodal_resampler/__pycache__/masked_drop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e5abccc21d4f30351d2803616c57214c7b0f331 Binary files /dev/null and b/VLMEvalKit-sudoku/llava/model/multimodal_resampler/__pycache__/masked_drop.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/llava/serve/gradio_web_server.py b/VLMEvalKit-sudoku/llava/serve/gradio_web_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4070dfaa3861b5460df57d02add37ecdf5067595 --- /dev/null +++ b/VLMEvalKit-sudoku/llava/serve/gradio_web_server.py @@ -0,0 +1,442 @@ +import argparse +import datetime +import json +import os +import time + +import gradio as gr +import requests + +from llava.conversation import default_conversation, conv_templates, SeparatorStyle +from llava.constants import LOGDIR +from llava.utils import build_logger, server_error_msg, violates_moderation, moderation_msg +import hashlib + + +logger = build_logger("gradio_web_server", "gradio_web_server.log") + +headers = {"User-Agent": "LLaVA Client"} + +no_change_btn = gr.Button.update() +enable_btn = gr.Button.update(interactive=True) +disable_btn = gr.Button.update(interactive=False) + +priority = { + "vicuna-13b": "aaaaaaa", + "koala-13b": "aaaaaab", +} + + +def get_conv_log_filename(): + t = datetime.datetime.now() + name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json") + return name + + +def get_model_list(): + ret = requests.post(args.controller_url + "/refresh_all_workers") + assert ret.status_code == 200 + ret = requests.post(args.controller_url + "/list_models") + models = ret.json()["models"] + models.sort(key=lambda x: priority.get(x, x)) + logger.info(f"Models: {models}") + return models + + +get_window_url_params = """ +function() { + const params = new URLSearchParams(window.location.search); + url_params = Object.fromEntries(params); + console.log(url_params); + return url_params; + } +""" + + +def load_demo(url_params, request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}") + + dropdown_update = gr.Dropdown.update(visible=True) + if "model" in url_params: + model = url_params["model"] + if model in models: + dropdown_update = gr.Dropdown.update(value=model, visible=True) + + state = default_conversation.copy() + return state, dropdown_update + + +def load_demo_refresh_model_list(request: gr.Request): + logger.info(f"load_demo. ip: {request.client.host}") + models = get_model_list() + state = default_conversation.copy() + dropdown_update = gr.Dropdown.update(choices=models, value=models[0] if len(models) > 0 else "") + return state, dropdown_update + + +def vote_last_response(state, vote_type, model_selector, request: gr.Request): + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(time.time(), 4), + "type": vote_type, + "model": model_selector, + "state": state.dict(), + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +def upvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"upvote. ip: {request.client.host}") + vote_last_response(state, "upvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def downvote_last_response(state, model_selector, request: gr.Request): + logger.info(f"downvote. ip: {request.client.host}") + vote_last_response(state, "downvote", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def flag_last_response(state, model_selector, request: gr.Request): + logger.info(f"flag. ip: {request.client.host}") + vote_last_response(state, "flag", model_selector, request) + return ("",) + (disable_btn,) * 3 + + +def regenerate(state, image_process_mode, request: gr.Request): + logger.info(f"regenerate. ip: {request.client.host}") + state.messages[-1][-1] = None + prev_human_msg = state.messages[-2] + if type(prev_human_msg[1]) in (tuple, list): + prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def clear_history(request: gr.Request): + logger.info(f"clear_history. ip: {request.client.host}") + state = default_conversation.copy() + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def add_text(state, text, image, image_process_mode, request: gr.Request): + logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}") + if len(text) <= 0 and image is None: + state.skip_next = True + return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 + if args.moderate: + flagged = violates_moderation(text) + if flagged: + state.skip_next = True + return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5 + + text = text[:1536] # Hard cut-off + if image is not None: + text = text[:1200] # Hard cut-off for images + if "" not in text: + # text = '' + text + text = text + "\n" + text = (text, image, image_process_mode) + if len(state.get_images(return_pil=True)) > 0: + state = default_conversation.copy() + state.append_message(state.roles[0], text) + state.append_message(state.roles[1], None) + state.skip_next = False + return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 + + +def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request, template_name=None): + logger.info(f"http_bot. ip: {request.client.host}") + start_tstamp = time.time() + model_name = model_selector + + if state.skip_next: + # This generate call is skipped due to invalid inputs + yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 + return + + if len(state.messages) == state.offset + 2: + # First round of conversation + if "llava" in model_name.lower(): + if "llama-2" in model_name.lower(): + template_name = "llava_llama_2" + elif "mistral" in model_name.lower() or "mixtral" in model_name.lower(): + if "orca" in model_name.lower(): + template_name = "mistral_orca" + elif "hermes" in model_name.lower(): + template_name = "mistral_direct" + else: + template_name = "mistral_instruct" + elif "zephyr" in model_name.lower(): + template_name = "mistral_zephyr" + elif "hermes" in model_name.lower(): + template_name = "mistral_direct" + elif "v1" in model_name.lower(): + if "mmtag" in model_name.lower(): + template_name = "llava_v1_mmtag" + elif "plain" in model_name.lower() and "finetune" not in model_name.lower(): + template_name = "llava_v1_mmtag" + else: + template_name = "llava_v1" + elif "mpt" in model_name.lower(): + template_name = "mpt" + else: + if "mmtag" in model_name.lower(): + template_name = "v0_plain" + elif "plain" in model_name.lower() and "finetune" not in model_name.lower(): + template_name = "v0_plain" + else: + template_name = "llava_v0" + elif "mistral" in model_name.lower() or "mixtral" in model_name.lower(): + if "orca" in model_name.lower(): + template_name = "mistral_orca" + elif "hermes" in model_name.lower(): + template_name = "mistral_direct" + else: + template_name = "mistral_instruct" + elif "hermes" in model_name.lower(): + template_name = "mistral_direct" + elif "zephyr" in model_name.lower(): + template_name = "mistral_zephyr" + elif "mpt" in model_name: + template_name = "mpt_text" + elif "llama-2" in model_name: + template_name = "llama_2" + else: + template_name = "vicuna_v1" + new_state = conv_templates[template_name].copy() + new_state.append_message(new_state.roles[0], state.messages[-2][1]) + new_state.append_message(new_state.roles[1], None) + state = new_state + + # Query worker address + controller_url = args.controller_url + ret = requests.post(controller_url + "/get_worker_address", json={"model": model_name}) + worker_addr = ret.json()["address"] + logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}") + + # No available worker + if worker_addr == "": + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + # Construct prompt + prompt = state.get_prompt() + + all_images = state.get_images(return_pil=True) + all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images] + for image, hash in zip(all_images, all_image_hash): + t = datetime.datetime.now() + filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg") + if not os.path.isfile(filename): + os.makedirs(os.path.dirname(filename), exist_ok=True) + image.save(filename) + + # Make requests + pload = { + "model": model_name, + "prompt": prompt, + "temperature": float(temperature), + "top_p": float(top_p), + "max_new_tokens": min(int(max_new_tokens), 1536), + "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2, + "images": f"List of {len(state.get_images())} images: {all_image_hash}", + } + logger.info(f"==== request ====\n{pload}") + + pload["images"] = state.get_images() + + state.messages[-1][-1] = "▌" + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + + try: + # Stream output + response = requests.post(worker_addr + "/worker_generate_stream", headers=headers, json=pload, stream=True, timeout=100) + last_print_time = time.time() + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode()) + if data["error_code"] == 0: + output = data["text"][len(prompt) :].strip() + state.messages[-1][-1] = output + "▌" + if time.time() - last_print_time > 0.05: + last_print_time = time.time() + yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 + else: + output = data["text"] + f" (error_code: {data['error_code']})" + state.messages[-1][-1] = output + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + time.sleep(0.03) + except requests.exceptions.RequestException as e: + state.messages[-1][-1] = server_error_msg + yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) + return + + state.messages[-1][-1] = state.messages[-1][-1][:-1] + yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5 + + finish_tstamp = time.time() + logger.info(f"{output}") + + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(finish_tstamp, 4), + "type": "chat", + "model": model_name, + "start": round(start_tstamp, 4), + "finish": round(start_tstamp, 4), + "state": state.dict(), + "images": all_image_hash, + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +title_markdown = """ +# 🌋 LLaVA: Large Language and Vision Assistant +[[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)] +""" + +tos_markdown = """ +### Terms of use +By using this service, users are required to agree to the following terms: +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. +Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. +For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. +""" + + +learn_more_markdown = """ +### License +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. +""" + +block_css = """ + +#buttons button { + min-width: min(120px,100%); +} + +""" + + +def build_demo(embed_mode): + textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False) + with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo: + state = gr.State() + + if not embed_mode: + gr.Markdown(title_markdown) + + with gr.Row(): + with gr.Column(scale=3): + with gr.Row(elem_id="model_selector_row"): + model_selector = gr.Dropdown(choices=models, value=models[0] if len(models) > 0 else "", interactive=True, show_label=False, container=False) + + imagebox = gr.Image(type="pil") + image_process_mode = gr.Radio(["Crop", "Resize", "Pad", "Default"], value="Default", label="Preprocess for non-square image", visible=False) + + cur_dir = os.path.dirname(os.path.abspath(__file__)) + gr.Examples( + examples=[ + [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"], + [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"], + ], + inputs=[imagebox, textbox], + ) + + with gr.Accordion("Parameters", open=False) as parameter_row: + temperature = gr.Slider( + minimum=0.0, + maximum=1.0, + value=0.2, + step=0.1, + interactive=True, + label="Temperature", + ) + top_p = gr.Slider( + minimum=0.0, + maximum=1.0, + value=0.7, + step=0.1, + interactive=True, + label="Top P", + ) + max_output_tokens = gr.Slider( + minimum=0, + maximum=1024, + value=512, + step=64, + interactive=True, + label="Max output tokens", + ) + + with gr.Column(scale=8): + chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550) + with gr.Row(): + with gr.Column(scale=8): + textbox.render() + with gr.Column(scale=1, min_width=50): + submit_btn = gr.Button(value="Send", variant="primary") + with gr.Row(elem_id="buttons") as button_row: + upvote_btn = gr.Button(value="👍 Upvote", interactive=False) + downvote_btn = gr.Button(value="👎 Downvote", interactive=False) + flag_btn = gr.Button(value="⚠️ Flag", interactive=False) + # stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False) + regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) + clear_btn = gr.Button(value="🗑️ Clear", interactive=False) + + if not embed_mode: + gr.Markdown(tos_markdown) + gr.Markdown(learn_more_markdown) + url_params = gr.JSON(visible=False) + + # Register listeners + btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] + upvote_btn.click(upvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False) + downvote_btn.click(downvote_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False) + flag_btn.click(flag_last_response, [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn], queue=False) + + 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) + + clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox] + btn_list, queue=False) + + textbox.submit(add_text, [state, textbox, imagebox, 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 + ) + + submit_btn.click(add_text, [state, textbox, imagebox, 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 + ) + + if args.model_list_mode == "once": + demo.load(load_demo, [url_params], [state, model_selector], _js=get_window_url_params, queue=False) + elif args.model_list_mode == "reload": + demo.load(load_demo_refresh_model_list, None, [state, model_selector], queue=False) + else: + raise ValueError(f"Unknown model list mode: {args.model_list_mode}") + + return demo + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int) + parser.add_argument("--controller-url", type=str, default="http://localhost:21001") + parser.add_argument("--concurrency-count", type=int, default=10) + parser.add_argument("--model-list-mode", type=str, default="once", choices=["once", "reload"]) + parser.add_argument("--share", action="store_true") + parser.add_argument("--moderate", action="store_true") + parser.add_argument("--embed", action="store_true") + args = parser.parse_args() + logger.info(f"args: {args}") + + models = get_model_list() + + logger.info(args) + demo = build_demo(args.embed) + demo.queue(concurrency_count=args.concurrency_count, api_open=False).launch(server_name=args.host, server_port=args.port, share=args.share) diff --git a/VLMEvalKit-sudoku/llava/train/llava_trainer_eval.py b/VLMEvalKit-sudoku/llava/train/llava_trainer_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..e82225852569674e9eea2cb8912153fba76b33fe --- /dev/null +++ b/VLMEvalKit-sudoku/llava/train/llava_trainer_eval.py @@ -0,0 +1,76 @@ +import json +import subprocess + +from llava.train.llava_trainer import LLaVATrainer + + +class LLaVAEvalTrainer(LLaVATrainer): + def evaluate(self, evaluate_args): + cmd = f"accelerate launch --num_processes {evaluate_args.eval_num_processes} -m lmms_eval \ + --model {evaluate_args.model} \ + --model_args {evaluate_args.model_args} \ + --tasks {evaluate_args.task_names} \ + --batch_size {evaluate_args.batch_size} \ + --log_samples_suffix {evaluate_args.log_samples_suffix} \ + --output_path {evaluate_args.output_path}" + if evaluate_args.limit: + cmd += f" --limit {evaluate_args.limit}" + if evaluate_args.num_fewshot: + cmd += f" --num_fewshot {evaluate_args.num_fewshot}" + if evaluate_args.gen_kwargs != "": + cmd += f" --gen_kwargs {evaluate_args.gen_kwargs}" + if evaluate_args.log_samples: + cmd += f" --log_samples" + else: + assert False, "Please log samples so that the result can be parsed" + results = subprocess.run([cmd], shell=True, capture_output=True, text=True) + try: + result_file_index_start = results.stdout.index("Saved samples to ") + result_file_index_end = results.stdout.index(f".json") + result_file_index_start += len("Saved samples to ") + file = results.stdout[result_file_index_start:result_file_index_end] + except: + result_file_index_start = results.stderr.index("Saved samples to ") + result_file_index_end = results.stderr.index(f".json") + result_file_index_start += len("Saved samples to ") + file = results.stderr[result_file_index_start:result_file_index_end] + file = file.split("/")[:-1] + file = "/".join(file) + "/results.json" + with open(file, "r") as f: + lmms_eval_results = json.load(f) + result_dict = {} + tasks_list = evaluate_args.task_names.split(",") + for task in tasks_list: + task_results = lmms_eval_results["results"][task] + for k, v in task_results.items(): + if k != "alias" and "stderr" not in k: + metric = k.split(",")[0] + result_dict[f"{task}_{metric}"] = v + return result_dict + + """def evaluate(self, evaluate_args): + initialize_tasks() + tasks_list = evaluate_args.task_names.split(",") + result_dict = {} + results = evaluator.simple_evaluate( + model=evaluate_args.model, + model_args=evaluate_args.model_args, + tasks=tasks_list, + num_fewshot=evaluate_args.num_fewshot, + batch_size=evaluate_args.batch_size, + device=evaluate_args.device, + limit=evaluate_args.limit, + check_integrity=evaluate_args.check_integrity, + show_task_to_terminal=evaluate_args.show_task_to_terminal, + log_samples=evaluate_args.log_samples, + gen_kwargs=evaluate_args.gen_kwargs, + cli_args=evaluate_args, + ) + for task in tasks_list: + task_results = results["results"][task] + for k,v in task_results.items(): + if k != "alias" and "stderr" not in k: + metric = k.split(",")[0] + result_dict[f"{task}_{metric}"] = v + + return result_dict""" diff --git a/VLMEvalKit-sudoku/llava/utils.py b/VLMEvalKit-sudoku/llava/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e004c33bc503d213df619dec948f39b4c13e53d --- /dev/null +++ b/VLMEvalKit-sudoku/llava/utils.py @@ -0,0 +1,198 @@ +import datetime +import logging +import logging.handlers +import os +import sys +import numpy as np + +import requests + +from llava.constants import LOGDIR + +server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" +moderation_msg = "I am sorry. Your input may violate our content moderation guidelines. Please avoid using harmful or offensive content." + +handler = None + +import torch.distributed as dist + +try: + import av + from decord import VideoReader, cpu +except ImportError: + print("Please install pyav to use video processing functions.") + +def process_video_with_decord(video_file, data_args): + vr = VideoReader(video_file, ctx=cpu(0), num_threads=1) + total_frame_num = len(vr) + video_time = total_frame_num / vr.get_avg_fps() + avg_fps = round(vr.get_avg_fps() / data_args.video_fps) + frame_idx = [i for i in range(0, total_frame_num, avg_fps)] + frame_time = [i/avg_fps for i in frame_idx] + + + if data_args.frames_upbound > 0: + if len(frame_idx) > data_args.frames_upbound or data_args.force_sample: + uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int) + frame_idx = uniform_sampled_frames.tolist() + frame_time = [i/vr.get_avg_fps() for i in frame_idx] + + video = vr.get_batch(frame_idx).asnumpy() + frame_time = ",".join([f"{i:.2f}s" for i in frame_time]) + + num_frames_to_sample = num_frames = len(frame_idx) + # https://github.com/dmlc/decord/issues/208 + vr.seek(0) + return video, video_time, frame_time, num_frames_to_sample + +def process_video_with_pyav(video_file, data_args): + container = av.open(video_file) + # !!! This is the only difference. Using auto threading + container.streams.video[0].thread_type = "AUTO" + + video_frames = [] + for packet in container.demux(): + if packet.stream.type == 'video': + for frame in packet.decode(): + video_frames.append(frame) + total_frame_num = len(video_frames) + video_time = video_frames[-1].time + avg_fps = round(total_frame_num / video_time / data_args.video_fps) + frame_idx = [i for i in range(0, total_frame_num, avg_fps)] + + if data_args.frames_upbound > 0: + if len(frame_idx) > data_args.frames_upbound: + uniform_sampled_frames = np.linspace(0, total_frame_num - 1, data_args.frames_upbound, dtype=int) + frame_idx = uniform_sampled_frames.tolist() + + + frames = [video_frames[i] for i in frame_idx] + return np.stack([x.to_ndarray(format="rgb24") for x in frames]) + + +def rank0_print(*args): + if dist.is_initialized(): + if dist.get_rank() == 0: + print(f"Rank {dist.get_rank()}: ", *args) + else: + print(*args) + + +def rank_print(*args): + if dist.is_initialized(): + print(f"Rank {dist.get_rank()}: ", *args) + else: + print(*args) + +def build_logger(logger_name, logger_filename): + global handler + + formatter = logging.Formatter( + fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + # Set the format of root handlers + if not logging.getLogger().handlers: + logging.basicConfig(level=logging.INFO) + logging.getLogger().handlers[0].setFormatter(formatter) + + # Redirect stdout and stderr to loggers + stdout_logger = logging.getLogger("stdout") + stdout_logger.setLevel(logging.INFO) + sl = StreamToLogger(stdout_logger, logging.INFO) + sys.stdout = sl + + stderr_logger = logging.getLogger("stderr") + stderr_logger.setLevel(logging.ERROR) + sl = StreamToLogger(stderr_logger, logging.ERROR) + sys.stderr = sl + + # Get logger + logger = logging.getLogger(logger_name) + logger.setLevel(logging.INFO) + + # Add a file handler for all loggers + if handler is None: + os.makedirs(LOGDIR, exist_ok=True) + filename = os.path.join(LOGDIR, logger_filename) + handler = logging.handlers.TimedRotatingFileHandler(filename, when="D", utc=True) + handler.setFormatter(formatter) + + for name, item in logging.root.manager.loggerDict.items(): + if isinstance(item, logging.Logger): + item.addHandler(handler) + + return logger + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + """ + + def __init__(self, logger, log_level=logging.INFO): + self.terminal = sys.stdout + self.logger = logger + self.log_level = log_level + self.linebuf = "" + + def __getattr__(self, attr): + return getattr(self.terminal, attr) + + def write(self, buf): + temp_linebuf = self.linebuf + buf + self.linebuf = "" + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross platform. + if line[-1] == "\n": + self.logger.log(self.log_level, line.rstrip()) + else: + self.linebuf += line + + def flush(self): + if self.linebuf != "": + self.logger.log(self.log_level, self.linebuf.rstrip()) + self.linebuf = "" + + +def disable_torch_init(): + """ + Disable the redundant torch default initialization to accelerate model creation. + """ + import torch + + setattr(torch.nn.Linear, "reset_parameters", lambda self: None) + setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None) + + +def violates_moderation(text): + """ + Check whether the text violates OpenAI moderation API. + """ + url = "https://api.openai.com/v1/moderations" + headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} + text = text.replace("\n", "") + data = "{" + '"input": ' + f'"{text}"' + "}" + data = data.encode("utf-8") + try: + ret = requests.post(url, headers=headers, data=data, timeout=5) + flagged = ret.json()["results"][0]["flagged"] + except requests.exceptions.RequestException as e: + print(f"######################### Moderation Error: {e} #########################") + flagged = False + except KeyError as e: + print(f"######################### Moderation Error: {e} #########################") + flagged = False + + return flagged + + +def pretty_print_semaphore(semaphore): + if semaphore is None: + return "None" + return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})" diff --git a/VLMEvalKit-sudoku/vlmeval/__pycache__/inference.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/__pycache__/inference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7471d7a6bb28dc25139bbcf9a5eaf5cdf93bb22 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/__pycache__/inference.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/__pycache__/tools.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/__pycache__/tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5df33c20d060f00280487838a70bb021566eea5 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/__pycache__/tools.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/api/__pycache__/reka.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/api/__pycache__/reka.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..557fcc61a402fcca9ea8f99dd0f78880b882d011 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/api/__pycache__/reka.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/api/bailingmm.py b/VLMEvalKit-sudoku/vlmeval/api/bailingmm.py new file mode 100644 index 0000000000000000000000000000000000000000..304b833dfd5e8ddaa674a0762b5a622bfc864f8f --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/bailingmm.py @@ -0,0 +1,90 @@ +import base64 +from vlmeval.smp import * +from vlmeval.api.base import BaseAPI +from vlmeval.dataset import DATASET_TYPE +from vlmeval.smp.vlm import encode_image_file_to_base64 +import time + + +class bailingMMWrapper(BaseAPI): + + is_api: bool = True + + def __init__(self, + model: str, + retry: int = 5, + key: str = None, + verbose: bool = True, + system_prompt: str = None, + max_tokens: int = 1024, + proxy: str = None, + **kwargs): + + self.model = model + self.fail_msg = 'Failed to obtain answer via bailingMM API.' + if key is None: + key = os.environ.get('BAILINGMM_API_KEY', None) + assert key is not None, ('Please set the API Key for bailingMM.') + self.key = key + self.headers = {"Content-Type": "application/json"} + super().__init__(retry=retry, system_prompt=system_prompt, verbose=verbose, **kwargs) + + def image_to_base64(self, image_path): + with open(image_path, 'rb') as image_file: + encoded_string = str(base64.b64encode(image_file.read()), 'utf-8') + return encoded_string + + def prepare_inputs(self, inputs): + msgs = cp.deepcopy(inputs) + content = [] + for i, msg in enumerate(msgs): + if msg['type'] == 'text': + pass + else: + try: + image_data = self.image_to_base64(msg['value']) + except Exception as e: + if self.verbose: + self.logger.error(e) + image_data = '' + msg['value'] = image_data + content.append(msg) + return content + + def generate_inner(self, inputs, **kwargs) -> str: + assert isinstance(inputs, str) or isinstance(inputs, list) + start = time.time() + inputs = [inputs] if isinstance(inputs, str) else inputs + + messages = self.prepare_inputs(inputs) + + service_url = "https://bailingchat.alipay.com/api/proxy/eval/antgmm/completions" + + payload = { + "structInput": json.dumps([{"role":"user","content":messages}]), + "sk": self.key, + "model": self.model, + "timeout": 180000 + } + response = requests.post(service_url, headers=self.headers, json=payload) + if self.verbose: + self.logger.info('Time for requesting is:') + self.logger.info(time.time() - start) + try: + assert response.status_code == 200 + output = json.loads(response.text) + answer = output['preds']['pred'] + if self.verbose: + self.logger.info(f'inputs: {inputs}\nanswer: {answer}') + return 0, answer, 'Succeeded! ' + except Exception as e: + if self.verbose: + self.logger.error(e) + self.logger.error(f'The input messages are {inputs}.') + return -1, self.fail_msg, '' + + +class bailingMMAPI(bailingMMWrapper): + + def generate(self, message, dataset=None): + return super(bailingMMAPI, self).generate(message, dataset=dataset) diff --git a/VLMEvalKit-sudoku/vlmeval/api/base.py b/VLMEvalKit-sudoku/vlmeval/api/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d5b6c092f38ca148cc74b2ad6f146f970dc7f062 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/base.py @@ -0,0 +1,296 @@ +import time +import random as rd +from abc import abstractmethod +import os.path as osp +import copy as cp +from ..smp import get_logger, parse_file, concat_images_vlmeval, LMUDataRoot, md5, decode_base64_to_image_file + + +class BaseAPI: + + allowed_types = ['text', 'image', 'video'] + INTERLEAVE = True + INSTALL_REQ = False + + def __init__(self, + retry=10, + wait=1, + system_prompt=None, + verbose=True, + fail_msg='Failed to obtain answer via API.', + **kwargs): + """Base Class for all APIs. + + Args: + retry (int, optional): The retry times for `generate_inner`. Defaults to 10. + wait (int, optional): The wait time after each failed retry of `generate_inner`. Defaults to 1. + system_prompt (str, optional): Defaults to None. + verbose (bool, optional): Defaults to True. + fail_msg (str, optional): The message to return when failed to obtain answer. + Defaults to 'Failed to obtain answer via API.'. + **kwargs: Other kwargs for `generate_inner`. + """ + + self.wait = wait + self.retry = retry + self.system_prompt = system_prompt + self.verbose = verbose + self.fail_msg = fail_msg + self.logger = get_logger('ChatAPI') + + if len(kwargs): + self.logger.info(f'BaseAPI received the following kwargs: {kwargs}') + self.logger.info('Will try to use them as kwargs for `generate`. ') + self.default_kwargs = kwargs + + @abstractmethod + def generate_inner(self, inputs, **kwargs): + """The inner function to generate the answer. + + Returns: + tuple(int, str, str): ret_code, response, log + """ + self.logger.warning('For APIBase, generate_inner is an abstract method. ') + assert 0, 'generate_inner not defined' + ret_code, answer, log = None, None, None + # if ret_code is 0, means succeed + return ret_code, answer, log + + def working(self): + """If the API model is working, return True, else return False. + + Returns: + bool: If the API model is working, return True, else return False. + """ + self.old_timeout = None + if hasattr(self, 'timeout'): + self.old_timeout = self.timeout + self.timeout = 120 + + retry = 5 + while retry > 0: + ret = self.generate('hello') + if ret is not None and ret != '' and self.fail_msg not in ret: + if self.old_timeout is not None: + self.timeout = self.old_timeout + return True + retry -= 1 + + if self.old_timeout is not None: + self.timeout = self.old_timeout + return False + + def check_content(self, msgs): + """Check the content type of the input. Four types are allowed: str, dict, liststr, listdict. + + Args: + msgs: Raw input messages. + + Returns: + str: The message type. + """ + if isinstance(msgs, str): + return 'str' + if isinstance(msgs, dict): + return 'dict' + if isinstance(msgs, list): + types = [self.check_content(m) for m in msgs] + if all(t == 'str' for t in types): + return 'liststr' + if all(t == 'dict' for t in types): + return 'listdict' + return 'unknown' + + def preproc_content(self, inputs): + """Convert the raw input messages to a list of dicts. + + Args: + inputs: raw input messages. + + Returns: + list(dict): The preprocessed input messages. Will return None if failed to preprocess the input. + """ + if self.check_content(inputs) == 'str': + return [dict(type='text', value=inputs)] + elif self.check_content(inputs) == 'dict': + assert 'type' in inputs and 'value' in inputs + return [inputs] + elif self.check_content(inputs) == 'liststr': + res = [] + for s in inputs: + mime, pth = parse_file(s) + if mime is None or mime == 'unknown': + res.append(dict(type='text', value=s)) + else: + res.append(dict(type=mime.split('/')[0], value=pth)) + return res + elif self.check_content(inputs) == 'listdict': + for item in inputs: + assert 'type' in item and 'value' in item + mime, s = parse_file(item['value']) + if mime is None: + assert item['type'] == 'text', item['value'] + else: + assert mime.split('/')[0] == item['type'] + item['value'] = s + return inputs + else: + return None + + # May exceed the context windows size, so try with different turn numbers. + def chat_inner(self, inputs, **kwargs): + _ = kwargs.pop('dataset', None) + while len(inputs): + try: + return self.generate_inner(inputs, **kwargs) + except Exception as e: + if self.verbose: + self.logger.info(f'{type(e)}: {e}') + inputs = inputs[1:] + while len(inputs) and inputs[0]['role'] != 'user': + inputs = inputs[1:] + continue + return -1, self.fail_msg + ': ' + 'Failed with all possible conversation turns.', None + + def chat(self, messages, **kwargs1): + """The main function for multi-turn chatting. Will call `chat_inner` with the preprocessed input messages.""" + assert hasattr(self, 'chat_inner'), 'The API model should has the `chat_inner` method. ' + for msg in messages: + assert isinstance(msg, dict) and 'role' in msg and 'content' in msg, msg + assert self.check_content(msg['content']) in ['str', 'dict', 'liststr', 'listdict'], msg + msg['content'] = self.preproc_content(msg['content']) + # merge kwargs + kwargs = cp.deepcopy(self.default_kwargs) + kwargs.update(kwargs1) + + answer = None + # a very small random delay [0s - 0.5s] + T = rd.random() * 0.5 + time.sleep(T) + + assert messages[-1]['role'] == 'user' + + for i in range(self.retry): + try: + ret_code, answer, log = self.chat_inner(messages, **kwargs) + if ret_code == 0 and self.fail_msg not in answer and answer != '': + if self.verbose: + print(answer) + return answer + elif self.verbose: + if not isinstance(log, str): + try: + log = log.text + except Exception as e: + self.logger.warning(f'Failed to parse {log} as an http response: {str(e)}. ') + self.logger.info(f'RetCode: {ret_code}\nAnswer: {answer}\nLog: {log}') + except Exception as err: + if self.verbose: + self.logger.error(f'An error occured during try {i}: ') + self.logger.error(f'{type(err)}: {err}') + # delay before each retry + T = rd.random() * self.wait * 2 + time.sleep(T) + + return self.fail_msg if answer in ['', None] else answer + + def preprocess_message_with_role(self, message): + system_prompt = '' + new_message = [] + + for data in message: + assert isinstance(data, dict) + role = data.pop('role', 'user') + if role == 'system': + system_prompt += data['value'] + '\n' + else: + new_message.append(data) + + if system_prompt != '': + if self.system_prompt is None: + self.system_prompt = system_prompt + else: + if system_prompt not in self.system_prompt: + self.system_prompt += '\n' + system_prompt + return new_message + + def generate(self, message, **kwargs1): + """The main function to generate the answer. Will call `generate_inner` with the preprocessed input messages. + + Args: + message: raw input messages. + + Returns: + str: The generated answer of the Failed Message if failed to obtain answer. + """ + if self.check_content(message) == 'listdict': + message = self.preprocess_message_with_role(message) + + assert self.check_content(message) in ['str', 'dict', 'liststr', 'listdict'], f'Invalid input type: {message}' + message = self.preproc_content(message) + assert message is not None and self.check_content(message) == 'listdict' + for item in message: + assert item['type'] in self.allowed_types, f'Invalid input type: {item["type"]}' + + # merge kwargs + kwargs = cp.deepcopy(self.default_kwargs) + kwargs.update(kwargs1) + + answer = None + # a very small random delay [0s - 0.5s] + T = rd.random() * 0.5 + time.sleep(T) + + for i in range(self.retry): + try: + ret_code, answer, log = self.generate_inner(message, **kwargs) + if ret_code == 0 and self.fail_msg not in answer and answer != '': + if self.verbose: + print(answer) + return answer + elif self.verbose: + if not isinstance(log, str): + try: + log = log.text + except Exception as e: + self.logger.warning(f'Failed to parse {log} as an http response: {str(e)}. ') + self.logger.info(f'RetCode: {ret_code}\nAnswer: {answer}\nLog: {log}') + except Exception as err: + if self.verbose: + self.logger.error(f'An error occured during try {i}: ') + self.logger.error(f'{type(err)}: {err}') + # delay before each retry + T = rd.random() * self.wait * 2 + time.sleep(T) + + return self.fail_msg if answer in ['', None] else answer + + def message_to_promptimg(self, message, dataset=None): + assert not self.INTERLEAVE + model_name = self.__class__.__name__ + import warnings + warnings.warn( + f'Model {model_name} does not support interleaved input. ' + 'Will use the first image and aggregated texts as prompt. ') + num_images = len([x for x in message if x['type'] == 'image']) + if num_images == 0: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + image = None + elif num_images == 1: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + image = [x['value'] for x in message if x['type'] == 'image'][0] + else: + prompt = '\n'.join([x['value'] if x['type'] == 'text' else '' for x in message]) + if dataset == 'BLINK': + image = concat_images_vlmeval( + [x['value'] for x in message if x['type'] == 'image'], + target_size=512) + else: + image = [x['value'] for x in message if x['type'] == 'image'][0] + return prompt, image + + def dump_image(self, line, dataset): + return self.dump_image_func(line) + + def set_dump_image(self, dump_image_func): + self.dump_image_func = dump_image_func diff --git a/VLMEvalKit-sudoku/vlmeval/api/claude.py b/VLMEvalKit-sudoku/vlmeval/api/claude.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbb35750cdafb55d102bead850b8765ee617dd6 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/claude.py @@ -0,0 +1,147 @@ +from vlmeval.smp import * +from vlmeval.api.base import BaseAPI +from time import sleep +import base64 +import mimetypes +from PIL import Image + +alles_url = 'https://openxlab.org.cn/gw/alles-apin-hub/v1/claude/v1/text/chat' +alles_headers = { + 'alles-apin-token': '', + 'Content-Type': 'application/json' +} +official_url = 'https://api.anthropic.com/v1/messages' +official_headers = { + 'x-api-key': '', + 'anthropic-version': '2023-06-01', + 'content-type': 'application/json' +} + + +class Claude_Wrapper(BaseAPI): + + is_api: bool = True + + def __init__(self, + backend: str = 'alles', + model: str = 'claude-3-opus-20240229', + key: str = None, + retry: int = 10, + timeout: int = 60, + system_prompt: str = None, + verbose: bool = True, + temperature: float = 0, + max_tokens: int = 2048, + **kwargs): + + if os.environ.get('ANTHROPIC_BACKEND', '') == 'official': + backend = 'official' + + assert backend in ['alles', 'official'], f'Invalid backend: {backend}' + self.backend = backend + self.url = alles_url if backend == 'alles' else official_url + self.model = model + self.temperature = temperature + self.max_tokens = max_tokens + self.headers = alles_headers if backend == 'alles' else official_headers + self.timeout = timeout + + if key is not None: + self.key = key + else: + self.key = os.environ.get('ALLES', '') if self.backend == 'alles' else os.environ.get('ANTHROPIC_API_KEY', '') # noqa: E501 + + if self.backend == 'alles': + self.headers['alles-apin-token'] = self.key + else: + self.headers['x-api-key'] = self.key + + super().__init__(retry=retry, verbose=verbose, system_prompt=system_prompt, **kwargs) + + def encode_image_file_to_base64(self, image_path, target_size=-1, fmt='.jpg'): + image = Image.open(image_path) + if fmt in ('.jpg', '.jpeg'): + format = 'JPEG' + elif fmt == '.png': + format = 'PNG' + else: + print(f'Unsupported image format: {fmt}, will cause media type match error.') + + return encode_image_to_base64(image, target_size=target_size, fmt=format) + + # inputs can be a lvl-2 nested list: [content1, content2, content3, ...] + # content can be a string or a list of image & text + def prepare_itlist(self, inputs): + assert np.all([isinstance(x, dict) for x in inputs]) + has_images = np.sum([x['type'] == 'image' for x in inputs]) + if has_images: + content_list = [] + for msg in inputs: + if msg['type'] == 'text' and msg['value'] != '': + content_list.append(dict(type='text', text=msg['value'])) + elif msg['type'] == 'image': + pth = msg['value'] + suffix = osp.splitext(pth)[-1].lower() + media_type = mimetypes.types_map.get(suffix, None) + assert media_type is not None + + content_list.append(dict( + type='image', + source={ + 'type': 'base64', + 'media_type': media_type, + 'data': self.encode_image_file_to_base64(pth, target_size=4096, fmt=suffix) + })) + else: + assert all([x['type'] == 'text' for x in inputs]) + text = '\n'.join([x['value'] for x in inputs]) + content_list = [dict(type='text', text=text)] + return content_list + + def prepare_inputs(self, inputs): + input_msgs = [] + assert isinstance(inputs, list) and isinstance(inputs[0], dict) + assert np.all(['type' in x for x in inputs]) or np.all(['role' in x for x in inputs]), inputs + if 'role' in inputs[0]: + assert inputs[-1]['role'] == 'user', inputs[-1] + for item in inputs: + input_msgs.append(dict(role=item['role'], content=self.prepare_itlist(item['content']))) + else: + input_msgs.append(dict(role='user', content=self.prepare_itlist(inputs))) + return input_msgs + + def generate_inner(self, inputs, **kwargs) -> str: + payload = { + 'model': self.model, + 'max_tokens': self.max_tokens, + 'messages': self.prepare_inputs(inputs), + **kwargs + } + if self.system_prompt is not None: + payload['system'] = self.system_prompt + + response = requests.request( + 'POST', self.url, headers=self.headers, data=json.dumps(payload), timeout=self.timeout * 1.1 + ) + ret_code = response.status_code + ret_code = 0 if (200 <= int(ret_code) < 300) else ret_code + answer = self.fail_msg + + try: + resp_struct = json.loads(response.text) + if self.backend == 'alles': + answer = resp_struct['data']['content'][0]['text'].strip() + elif self.backend == 'official': + answer = resp_struct['content'][0]['text'].strip() + except Exception as err: + if self.verbose: + self.logger.error(f'{type(err)}: {err}') + self.logger.error(response.text if hasattr(response, 'text') else response) + + return ret_code, answer, response + + +class Claude3V(Claude_Wrapper): + + def generate(self, message, dataset=None): + return super(Claude_Wrapper, self).generate(message) diff --git a/VLMEvalKit-sudoku/vlmeval/api/hunyuan.py b/VLMEvalKit-sudoku/vlmeval/api/hunyuan.py new file mode 100644 index 0000000000000000000000000000000000000000..482225758476f2a034fecb2b5ae30b6f64d148e3 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/hunyuan.py @@ -0,0 +1,183 @@ +from vlmeval.smp import * +import os +import sys +from vlmeval.api.base import BaseAPI +import math +from vlmeval.dataset import DATASET_TYPE +from vlmeval.dataset import img_root_map +from io import BytesIO +import pandas as pd +import requests +import json +import base64 +import time + + +class HunyuanWrapper(BaseAPI): + + is_api: bool = True + _apiVersion = '2024-12-31' + _service = 'hunyuan' + + def __init__(self, + model: str = 'hunyuan-standard-vision', + retry: int = 5, + secret_key: str = None, + secret_id: str = None, + verbose: bool = True, + system_prompt: str = None, + temperature: float = 0, + timeout: int = 60, + api_base: str = 'hunyuan.tencentcloudapi.com', + **kwargs): + + self.model = model + self.cur_idx = 0 + self.fail_msg = 'Failed to obtain answer via API. ' + self.temperature = temperature + + warnings.warn('You may need to set the env variable HUNYUAN_SECRET_ID & HUNYUAN_SECRET_KEY to use Hunyuan. ') + + secret_key = os.environ.get('HUNYUAN_SECRET_KEY', secret_key) + assert secret_key is not None, 'Please set the environment variable HUNYUAN_SECRET_KEY. ' + secret_id = os.environ.get('HUNYUAN_SECRET_ID', secret_id) + assert secret_id is not None, 'Please set the environment variable HUNYUAN_SECRET_ID. ' + + self.model = model + self.endpoint = api_base + self.secret_id = secret_id + self.secret_key = secret_key + self.timeout = timeout + + try: + from tencentcloud.common import credential + from tencentcloud.common.profile.client_profile import ClientProfile + from tencentcloud.common.profile.http_profile import HttpProfile + from tencentcloud.hunyuan.v20230901 import hunyuan_client + except ImportError as err: + self.logger.critical('Please install tencentcloud-sdk-python to use Hunyuan API. ') + raise err + + super().__init__(retry=retry, system_prompt=system_prompt, verbose=verbose, **kwargs) + + cred = credential.Credential(self.secret_id, self.secret_key) + httpProfile = HttpProfile(reqTimeout=300) + httpProfile.endpoint = self.endpoint + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + self.client = hunyuan_client.HunyuanClient(cred, '', clientProfile) + self.logger.info( + f'Using Endpoint: {self.endpoint}; API Secret ID: {self.secret_id}; API Secret Key: {self.secret_key}' + ) + + def use_custom_prompt(self, dataset_name): + if DATASET_TYPE(dataset_name) == 'MCQ': + return True + else: + return False + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + + tgt_path = self.dump_image(line, dataset) + + question = line['question'] + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = 'Options:\n' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = '' + if hint is not None: + prompt += f'Hint: {hint}\n' + prompt += f'Question: {question}\n' + if len(options): + prompt += options_prompt + prompt += 'Answer with the option letter from the given choices directly.' + + msgs = [] + if isinstance(tgt_path, list): + msgs.extend([dict(type='image', value=p) for p in tgt_path]) + else: + msgs = [dict(type='image', value=tgt_path)] + msgs.append(dict(type='text', value=prompt)) + return msgs + + # inputs can be a lvl-2 nested list: [content1, content2, content3, ...] + # content can be a string or a list of image & text + def prepare_itlist(self, inputs): + assert np.all([isinstance(x, dict) for x in inputs]) + has_images = np.sum([x['type'] == 'image' for x in inputs]) + if has_images: + content_list = [] + for msg in inputs: + if msg['type'] == 'text': + content_list.append(dict(Type='text', Text=msg['value'])) + elif msg['type'] == 'image': + from PIL import Image + img = Image.open(msg['value']) + b64 = encode_image_to_base64(img) + img_struct = dict(Url=f'data:image/jpeg;base64,{b64}') + content_list.append(dict(Type='image_url', ImageUrl=img_struct)) + else: + assert all([x['type'] == 'text' for x in inputs]) + text = '\n'.join([x['value'] for x in inputs]) + content_list = [dict(Type='text', Text=text)] + return content_list + + def prepare_inputs(self, inputs): + input_msgs = [] + if self.system_prompt is not None: + input_msgs.append(dict(Role='system', Content=self.system_prompt)) + assert isinstance(inputs, list) and isinstance(inputs[0], dict) + assert np.all(['type' in x for x in inputs]) or np.all(['role' in x for x in inputs]), inputs + if 'role' in inputs[0]: + assert inputs[-1]['role'] == 'user', inputs[-1] + for item in inputs: + input_msgs.append(dict(Role=item['role'], Contents=self.prepare_itlist(item['content']))) + else: + input_msgs.append(dict(Role='user', Contents=self.prepare_itlist(inputs))) + return input_msgs + + def generate_inner(self, inputs, **kwargs) -> str: + from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException + from tencentcloud.hunyuan.v20230901 import models + + input_msgs = self.prepare_inputs(inputs) + temperature = kwargs.pop('temperature', self.temperature) + + payload = dict( + Model=self.model, + Messages=input_msgs, + Temperature=temperature, + TopK=1, + **kwargs) + + try: + req = models.ChatCompletionsRequest() + req.from_json_string(json.dumps(payload)) + resp = self.client.ChatCompletions(req) + resp = json.loads(resp.to_json_string()) + answer = resp['Choices'][0]['Message']['Content'] + return 0, answer, resp + except TencentCloudSDKException as e: + self.logger.error(f'Got error code: {e.get_code()}') + if e.get_code() == 'ClientNetworkError': + return -1, self.fail_msg + e.get_code(), None + elif e.get_code() in ['InternalError', 'ServerNetworkError']: + return -1, self.fail_msg + e.get_code(), None + elif e.get_code() in ['LimitExceeded']: + return -1, self.fail_msg + e.get_code(), None + else: + return -1, self.fail_msg + str(e), None + + +class HunyuanVision(HunyuanWrapper): + + def generate(self, message, dataset=None): + return super(HunyuanVision, self).generate(message) diff --git a/VLMEvalKit-sudoku/vlmeval/api/qwen_api.py b/VLMEvalKit-sudoku/vlmeval/api/qwen_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7cd72cad6d73093900ac0a799b34b98f3ce637a4 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/qwen_api.py @@ -0,0 +1,74 @@ +from http import HTTPStatus +import os +from vlmeval.api.base import BaseAPI +from vlmeval.smp import * + + +# Note: This is a pure language model API. +class QwenAPI(BaseAPI): + + is_api: bool = True + + def __init__(self, + model: str = 'qwen-max-1201', + retry: int = 5, + verbose: bool = True, + seed: int = 2680, + temperature: float = 0.0, + system_prompt: str = None, + key: str = None, + max_tokens: int = 2048, + proxy: str = None, + **kwargs): + + assert model in ['qwen-turbo', 'qwen-plus', 'qwen-max', 'qwen-max-1201', 'qwen-max-longcontext'] + self.model = model + import dashscope + self.fail_msg = 'Failed to obtain answer via API. ' + self.max_tokens = max_tokens + self.temperature = temperature + self.seed = seed + if key is None: + key = os.environ.get('DASHSCOPE_API_KEY', None) + assert key is not None, ( + 'Please set the API Key (obtain it here: ' + 'https://help.aliyun.com/zh/dashscope/developer-reference/vl-plus-quick-start)' + ) + dashscope.api_key = key + if proxy is not None: + proxy_set(proxy) + super().__init__(retry=retry, system_prompt=system_prompt, verbose=verbose, **kwargs) + + @staticmethod + def build_msgs(msgs_raw, system_prompt=None): + msgs = cp.deepcopy(msgs_raw) + ret = [] + if system_prompt is not None: + ret.append(dict(role='system', content=system_prompt)) + for i, msg in enumerate(msgs): + role = 'user' if i % 2 == 0 else 'assistant' + ret.append(dict(role=role, content=msg)) + return ret + + def generate_inner(self, inputs, **kwargs) -> str: + from dashscope import MultiModalConversation + assert isinstance(inputs, str) or isinstance(inputs, list) + inputs = [inputs] if isinstance(inputs, str) else inputs + messages = self.build_msgs(msgs_raw=inputs, system_prompt=self.system_prompt) + + import dashscope + response = dashscope.Generation.call( + model=self.model, + messages=messages, + seed=self.seed, + temperature=self.temperature, + max_tokens=self.max_tokens, + result_format='message', # set the result to be "message" format. + ) + if response.status_code != HTTPStatus.OK: + return -1, 'Error: Bad Response Statuse Code. ', f'The response status code is {response.status_code}. ' + + try: + return 0, response['output']['choices'][0]['message']['content'].strip(), 'Succeeded! ' + except Exception as err: + return -1, f'Error: Failed to parse the response. {err}', response diff --git a/VLMEvalKit-sudoku/vlmeval/api/reka.py b/VLMEvalKit-sudoku/vlmeval/api/reka.py new file mode 100644 index 0000000000000000000000000000000000000000..63c8136be2443ad795a0134424c0b8dea64a308d --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/api/reka.py @@ -0,0 +1,59 @@ +from vlmeval.smp import * +from vlmeval.api.base import BaseAPI +from time import sleep +import mimetypes + + +class Reka_Wrapper(BaseAPI): + + is_api: bool = True + INTERLEAVE: bool = False + + def __init__(self, + model: str = 'reka-flash-20240226', + key: str = None, + retry: int = 10, + system_prompt: str = None, + verbose: bool = True, + temperature: float = 0, + max_tokens: int = 1024, + **kwargs): + + try: + import reka + except ImportError: + raise ImportError('Please install reka by running "pip install reka-api"') + + self.model = model + default_kwargs = dict(temperature=temperature, request_output_len=max_tokens) + default_kwargs.update(kwargs) + self.kwargs = default_kwargs + if key is not None: + self.key = key + else: + self.key = os.environ.get('REKA_API_KEY', '') + super().__init__(retry=retry, verbose=verbose, system_prompt=system_prompt, **kwargs) + + def generate_inner(self, inputs, **kwargs) -> str: + import reka + reka.API_KEY = self.key + dataset = kwargs.pop('dataset', None) + prompt, image_path = self.message_to_promptimg(inputs, dataset=dataset) + image_b64 = encode_image_file_to_base64(image_path) + + response = reka.chat( + model_name=self.model, + human=prompt, + media_url=f'data:image/jpeg;base64,{image_b64}', + **self.kwargs) + + try: + return 0, response['text'], response + except Exception as err: + return -1, self.fail_msg + str(err), response + + +class Reka(Reka_Wrapper): + + def generate(self, message, dataset=None): + return super(Reka_Wrapper, self).generate(message) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__init__.py b/VLMEvalKit-sudoku/vlmeval/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2c54e00397f1a4c6ffa0a3266b82c40759fd1b --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/__init__.py @@ -0,0 +1,317 @@ +import warnings + +from .image_base import img_root_map, ImageBaseDataset +from .image_caption import ImageCaptionDataset +from .image_yorn import ImageYORNDataset +from .image_mcq import ( + ImageMCQDataset, MMMUDataset, CustomMCQDataset, MUIRDataset, GMAIMMBenchDataset, MMERealWorld, HRBenchDataset, + NaturalBenchDataset, WeMath, MMMUProDataset, VMCBenchDataset, MedXpertQA_MM_test, LEGO, VisuLogic, CVBench, TDBench, + MicroBench, OmniMedVQA, MSEarthMCQ, VLMBlind, SCAM, _3DSRBench, AffordanceDataset, OmniEarthMCQBench, XLRSBench, + TreeBench, CVQA, TopViewRS, ShapeGrid +) +from .image_mt import MMDUDataset +from .image_vqa import ( + ImageVQADataset, MathVision, OCRBench, MathVista, LLaVABench, LLaVABench_KO, VGRPBench, MMVet, MTVQADataset, + TableVQABench, CustomVQADataset, CRPE, MathVerse, OlympiadBench, SeePhys, QSpatial, VizWiz, MMNIAH, LogicVista, + MME_CoT, MMSci_Captioning, Physics_yale, TDBenchGrounding, WildDocBenchmark, OCR_Reasoning, PhyX, CountBenchQA, + ZEROBench, Omni3DBench, TallyQA, MMEReasoning, MMVMBench, BMMR, OCRBench_v2, AyaVisionBench +) + +from .image_ccocr import CCOCRDataset +from .image_shortqa import ImageShortQADataset, PathVQA_VAL, PathVQA_TEST +from .text_mcq import CustomTextMCQDataset, TextMCQDataset + +from .vcr import VCRDataset +from .mmlongbench import MMLongBench +from .dude import DUDE +from .slidevqa import SlideVQA +from .vl_rewardbench import VLRewardBench +from .vlm2bench import VLM2Bench +from .vlmbias import VLMBias +from .spatial457 import Spatial457 +from .charxiv import CharXiv + +from .mmbench_video import MMBenchVideo +from .videomme import VideoMME +from .video_holmes import Video_Holmes +from .mvbench import MVBench, MVBench_MP4 +from .tamperbench import MVTamperBench +from .miabench import MIABench +from .mlvu import MLVU, MLVU_MCQ, MLVU_OpenEnded +from .tempcompass import TempCompass, TempCompass_Captioning, TempCompass_MCQ, TempCompass_YorN +from .longvideobench import LongVideoBench +from .video_concat_dataset import ConcatVideoDataset +from .mmgenbench import MMGenBench +from .cgbench import CGBench_MCQ_Grounding_Mini, CGBench_OpenEnded_Mini, CGBench_MCQ_Grounding, CGBench_OpenEnded +from .CGAVCounting.cg_av_counting import CGAVCounting + +from .megabench import MEGABench +from .moviechat1k import MovieChat1k +from .video_mmlu import Video_MMLU_CAP, Video_MMLU_QA +from .vdc import VDC +from .vcrbench import VCRBench +from .gobench import GOBenchDataset +from .sfebench import SFE +from .visfactor import VisFactor +from .ost_bench import OSTDataset + +from .EgoExoBench.egoexobench import EgoExoBench_MCQ + +from .worldsense import WorldSense +from .qbench_video import QBench_Video, QBench_Video_MCQ, QBench_Video_VQA + +from .cmmmu import CMMMU +from .emma import EMMADataset +from .wildvision import WildVision +from .mmmath import MMMath +from .dynamath import Dynamath +from .creation import CreationMMBenchDataset +from .mmalignbench import MMAlignBench +from .utils import * +from .video_dataset_config import * +from ..smp import * +from .OmniDocBench.omnidocbench import OmniDocBench +from .moat import MOAT +from .GUI.screenspot import ScreenSpot +from .GUI.screenspot_v2 import ScreenSpotV2 +from .GUI.screenspot_pro import ScreenSpot_Pro +from .mmifeval import MMIFEval +from .chartmimic import ChartMimic +from .m4bench import M4Bench + + +class ConcatDataset(ImageBaseDataset): + # This dataset takes multiple dataset names as input and aggregate them into a single dataset. + # Each single dataset should not have a field named `SUB_DATASET` + + DATASET_SETS = { + 'MMMB': ['MMMB_ar', 'MMMB_cn', 'MMMB_en', 'MMMB_pt', 'MMMB_ru', 'MMMB_tr'], + 'MTL_MMBench_DEV': [ + 'MMBench_dev_ar', 'MMBench_dev_cn', 'MMBench_dev_en', + 'MMBench_dev_pt', 'MMBench_dev_ru', 'MMBench_dev_tr' + ], + 'ScreenSpot_Pro': [ + 'ScreenSpot_Pro_Development', 'ScreenSpot_Pro_Creative', 'ScreenSpot_Pro_CAD', + 'ScreenSpot_Pro_Scientific', 'ScreenSpot_Pro_Office', 'ScreenSpot_Pro_OS' + ], + 'ScreenSpot': ['ScreenSpot_Mobile', 'ScreenSpot_Desktop', 'ScreenSpot_Web'], + 'ScreenSpot_v2': ['ScreenSpot_v2_Mobile', 'ScreenSpot_v2_Desktop', 'ScreenSpot_v2_Web'], + 'M4Bench': ['State_Invariance', 'State_Comparison', 'Spatial_Perception', 'Instance_Comparison', 'Detailed_Difference'], # noqa: E501 + } + + def __init__(self, dataset): + datasets = self.DATASET_SETS[dataset] + self.dataset_map = {} + # The name of the compliation + self.dataset_name = dataset + self.datasets = datasets + for dname in datasets: + dataset = build_dataset(dname) + assert dataset is not None, dataset + self.dataset_map[dname] = dataset + TYPES = [x.TYPE for x in self.dataset_map.values()] + MODALITIES = [x.MODALITY for x in self.dataset_map.values()] + assert np.all([x == TYPES[0] for x in TYPES]), (datasets, TYPES) + assert np.all([x == MODALITIES[0] for x in MODALITIES]), (datasets, MODALITIES) + self.TYPE = TYPES[0] + self.MODALITY = MODALITIES[0] + data_all = [] + for dname in datasets: + data = self.dataset_map[dname].data + data['SUB_DATASET'] = [dname] * len(data) + if 'image' in data: + data_new = localize_df(data, dname, nproc=16) + data_all.append(data_new) + else: + data_all.append(data) + + data = pd.concat(data_all) + data['original_index'] = data.pop('index') + data['index'] = np.arange(len(data)) + self.data = data + + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + idx = line['original_index'] + dname = line['SUB_DATASET'] + org_data = self.dataset_map[dname].data + org_line = cp.deepcopy(org_data[org_data['index'] == idx]).iloc[0] + return self.dataset_map[dname].build_prompt(org_line) + + def dump_image(self, line): + # Assert all images are pre-dumped + assert 'image' not in line + assert 'image_path' in line + tgt_path = toliststr(line['image_path']) + return tgt_path + + @classmethod + def supported_datasets(cls): + return list(cls.DATASET_SETS) + + def evaluate(self, eval_file, **judge_kwargs): + # First, split the eval_file by dataset + data_all = load(eval_file) + for dname in self.datasets: + tgt = eval_file.replace(self.dataset_name, dname) + data_sub = data_all[data_all['SUB_DATASET'] == dname] + data_sub.pop('index') + data_sub['index'] = data_sub.pop('original_index') + data_sub.pop('SUB_DATASET') + dump(data_sub, tgt) + # Then, evaluate each dataset separately + df_all = [] + dict_all = {} + # One of the vars will be used to aggregate results + for dname in self.datasets: + tgt = eval_file.replace(self.dataset_name, dname) + res = self.dataset_map[dname].evaluate(tgt, **judge_kwargs) + if isinstance(res, pd.DataFrame): + res['DATASET'] = [dname] * len(res) + df_all.append(res) + elif isinstance(res, dict): + res = {f'{dname}:{k}': v for k, v in res.items()} + dict_all.update(res) + else: + raise NotImplementedError(f'Unknown result type {type(res)}') + + if len(df_all): + result = pd.concat(df_all) + score_file = get_intermediate_file_path(eval_file, '_acc', 'csv') + dump(result, score_file) + return result + else: + score_file = get_intermediate_file_path(eval_file, '_score', 'json') + dump(dict_all, score_file) + return dict_all + + +# Add new supported dataset class here +IMAGE_DATASET = [ + ImageCaptionDataset, ImageYORNDataset, ImageMCQDataset, ImageVQADataset, + MathVision, MMMUDataset, OCRBench, MathVista, LLaVABench, LLaVABench_KO, VGRPBench, MMVet, + MTVQADataset, TableVQABench, MMLongBench, VCRDataset, MMDUDataset, DUDE, + SlideVQA, MUIRDataset, CCOCRDataset, GMAIMMBenchDataset, MMERealWorld, + HRBenchDataset, CRPE, MathVerse, NaturalBenchDataset, MIABench, + OlympiadBench, SeePhys,WildVision, MMMath, QSpatial, Dynamath, MMGenBench, VizWiz, + MMNIAH, CMMMU, VLRewardBench, WeMath, LogicVista, MMMUProDataset, + CreationMMBenchDataset, ImageShortQADataset, MMAlignBench, OmniDocBench, + VLM2Bench, VMCBenchDataset, EMMADataset, MME_CoT, MOAT, MedXpertQA_MM_test, + LEGO, MMSci_Captioning, Physics_yale, ScreenSpot_Pro, ScreenSpot, + ScreenSpotV2, MMIFEval, Spatial457, VisuLogic, CVBench, PathVQA_VAL, + PathVQA_TEST, TDBench, TDBenchGrounding, MicroBench, CharXiv, OmniMedVQA, + WildDocBenchmark, MSEarthMCQ, OCR_Reasoning, PhyX, VLMBlind, CountBenchQA, + ZEROBench, SCAM, Omni3DBench, TallyQA, _3DSRBench, BMMR, AffordanceDataset, + MMEReasoning, GOBenchDataset, SFE, ChartMimic, MMVMBench, XLRSBench, + OmniEarthMCQBench, VisFactor, OSTDataset, OCRBench_v2, TreeBench, CVQA, M4Bench, + AyaVisionBench, TopViewRS, VLMBias, ShapeGrid +] + +VIDEO_DATASET = [ + MMBenchVideo, VideoMME, MVBench, MVBench_MP4, MVTamperBench, + LongVideoBench, WorldSense, VDC, MovieChat1k, MEGABench, + MLVU, MLVU_MCQ, MLVU_OpenEnded, + TempCompass, TempCompass_MCQ, TempCompass_Captioning, TempCompass_YorN, + CGBench_MCQ_Grounding_Mini, CGBench_OpenEnded_Mini, CGBench_MCQ_Grounding, CGBench_OpenEnded, + QBench_Video, QBench_Video_MCQ, QBench_Video_VQA, + Video_MMLU_CAP, Video_MMLU_QA, + Video_Holmes, VCRBench, CGAVCounting, + EgoExoBench_MCQ, +] + +TEXT_DATASET = [ + TextMCQDataset +] + +CUSTOM_DATASET = [ + CustomMCQDataset, CustomVQADataset, CustomTextMCQDataset +] + +DATASET_COLLECTION = [ConcatDataset, ConcatVideoDataset] + +DATASET_CLASSES = IMAGE_DATASET + VIDEO_DATASET + TEXT_DATASET + CUSTOM_DATASET + DATASET_COLLECTION # noqa: E501 +SUPPORTED_DATASETS = [] +for DATASET_CLS in DATASET_CLASSES: + SUPPORTED_DATASETS.extend(DATASET_CLS.supported_datasets()) + + +def DATASET_TYPE(dataset, *, default: str = 'MCQ') -> str: + for cls in DATASET_CLASSES: + if dataset in cls.supported_datasets(): + if hasattr(cls, 'TYPE'): + return cls.TYPE + # Have to add specific routine to handle ConcatDataset + if dataset in ConcatDataset.DATASET_SETS: + dataset_list = ConcatDataset.DATASET_SETS[dataset] + TYPES = [DATASET_TYPE(dname) for dname in dataset_list] + assert np.all([x == TYPES[0] for x in TYPES]), (dataset_list, TYPES) + return TYPES[0] + + if 'openended' in dataset.lower(): + return 'VQA' + warnings.warn(f'Dataset {dataset} is a custom one and not annotated as `openended`, will treat as {default}. ') # noqa: E501 + return default + + +def DATASET_MODALITY(dataset, *, default: str = 'IMAGE') -> str: + if dataset is None: + warnings.warn(f'Dataset is not specified, will treat modality as {default}. ') + return default + for cls in DATASET_CLASSES: + if dataset in cls.supported_datasets(): + if hasattr(cls, 'MODALITY'): + return cls.MODALITY + # Have to add specific routine to handle ConcatDataset + if dataset in ConcatDataset.DATASET_SETS: + dataset_list = ConcatDataset.DATASET_SETS[dataset] + MODALITIES = [DATASET_MODALITY(dname) for dname in dataset_list] + assert np.all([x == MODALITIES[0] for x in MODALITIES]), (dataset_list, MODALITIES) + return MODALITIES[0] + + if 'VIDEO' in dataset.lower(): + return 'VIDEO' + elif 'IMAGE' in dataset.lower(): + return 'IMAGE' + warnings.warn(f'Dataset {dataset} is a custom one, will treat modality as {default}. ') + return default + + +def build_dataset(dataset_name, **kwargs): + for cls in DATASET_CLASSES: + if dataset_name in supported_video_datasets: + return supported_video_datasets[dataset_name](**kwargs) + elif dataset_name in cls.supported_datasets(): + return cls(dataset=dataset_name, **kwargs) + + warnings.warn(f'Dataset {dataset_name} is not officially supported. ') + data_file = osp.join(LMUDataRoot(), f'{dataset_name}.tsv') + if not osp.exists(data_file): + warnings.warn(f'Data file {data_file} does not exist. Dataset building failed. ') + return None + + data = load(data_file) + if 'question' not in [x.lower() for x in data.columns]: + warnings.warn(f'Data file {data_file} does not have a `question` column. Dataset building failed. ') + return None + + if 'A' in data and 'B' in data: + if 'image' in data or 'image_path' in data: + warnings.warn(f'Will assume unsupported dataset {dataset_name} as a Custom MCQ dataset. ') + return CustomMCQDataset(dataset=dataset_name, **kwargs) + else: + warnings.warn(f'Will assume unsupported dataset {dataset_name} as a Custom Text MCQ dataset. ') + return CustomTextMCQDataset(dataset=dataset_name, **kwargs) + else: + warnings.warn(f'Will assume unsupported dataset {dataset_name} as a Custom VQA dataset. ') + return CustomVQADataset(dataset=dataset_name, **kwargs) + + +def infer_dataset_basename(dataset_name): + basename = "_".join(dataset_name.split("_")[:-1]) + return basename + + +__all__ = [ + 'build_dataset', 'img_root_map', 'build_judge', 'extract_answer_from_item', 'prefetch_answer', 'DEBUG_MESSAGE' +] + [cls.__name__ for cls in DATASET_CLASSES] diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/chartmimic.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/chartmimic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2837e9d77917af100f5be65c34e9fa00f1794ae Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/chartmimic.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/m4bench.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/m4bench.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f999b1ac03afbec38c28ff804fc84a25aa21fe16 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/m4bench.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/miabench.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/miabench.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d21cd918d5dc751c33b7b7286d4bf4abc960497 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/miabench.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/ost_bench.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/ost_bench.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518adeacb84fcffe429a60bf4b55afa90afae874 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/ost_bench.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/qbench_video.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/qbench_video.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65e05b049c42403d9c3645f08103955fbf23aa9a Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/qbench_video.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/video_dataset_config.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/video_dataset_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a21556d51cd3b86b3eacb60966c71a6d2fcdbd54 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/video_dataset_config.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/emma.py b/VLMEvalKit-sudoku/vlmeval/dataset/emma.py new file mode 100644 index 0000000000000000000000000000000000000000..b5dc4952385f8bc67a9ddd658a9c54c8d049a2f1 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/emma.py @@ -0,0 +1,56 @@ +from vlmeval import * +from .image_shortqa import ImageShortQADataset +from .image_mcq import MMMUDataset + + +class EMMADataset(ImageShortQADataset): + + COT_INST = "Please solve the problem step by step. " + DIRECT_INST = "Please ensure that your output only contains the final answer without any additional content (such as intermediate reasoning steps)." # noqa: E501 + MCQ_FMT = "{context}\n\n{question}\n\n{options}\n\nAnswer with the option's letter from the given choices. " + OPEN_FMT = "{context}\n\n{question}\n\nAnswer the question using a single word or phrase. " + + DATASET_URL = { + 'EMMA': 'https://opencompass.openxlab.space/utils/VLMEval/EMMA.tsv', + 'EMMA_COT': 'https://opencompass.openxlab.space/utils/VLMEval/EMMA.tsv' + } + + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + + if self.meta_only: + tgt_path = toliststr(line['image_path']) + else: + tgt_path = self.dump_image(line) + + context = line['context'] + question = line['question'] + example = "" + _ = {} + if line['type'] == 'MCQ': + for ch in string.ascii_uppercase: + if ch in line and not pd.isna(line[ch]): + example += f"{ch}: {line[ch]}\n" + + prompt_tmpl = EMMADataset.MCQ_FMT + if not pd.isna(context) and context is not None: + prompt = prompt_tmpl.format(context=context, question=question, options=example) + else: + prompt = prompt_tmpl.split('{context}\n\n')[1].format(question=question, options=example) + prompt += EMMADataset.COT_INST if 'COT' in self.dataset_name else EMMADataset.DIRECT_INST + else: + prompt_tmpl = EMMADataset.OPEN_FMT + if not pd.isna(context) and context is not None: + prompt = prompt_tmpl.format(context=context, question=question) + else: + prompt = prompt_tmpl.split('{context}\n\n')[1].format(question=question) + prompt += EMMADataset.COT_INST if 'COT' in self.dataset_name else EMMADataset.DIRECT_INST + + msgs = [] + if isinstance(tgt_path, list): + msgs.extend([dict(type='image', value=p) for p in tgt_path]) + else: + msgs = [dict(type='image', value=tgt_path)] + msgs.append(dict(type='text', value=prompt)) + return MMMUDataset.split_MMMU(msgs) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/image_mt.py b/VLMEvalKit-sudoku/vlmeval/dataset/image_mt.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd72d72624c8c1f0341c36025ded6e36980d527 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/image_mt.py @@ -0,0 +1,128 @@ +from .image_base import ImageBaseDataset +from .utils.judge_util import build_judge +from ..smp import * +from ..smp.file import get_intermediate_file_path +from ..utils import track_progress_rich + + +class ImageMTDataset(ImageBaseDataset): + + TYPE = 'MT' + + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + + if self.meta_only: + tgt_path = toliststr(line['image_path']) + else: + tgt_path = self.dump_image(line) + + questions = toliststr(line['question']) + if 'answer' in line: + answers = toliststr(line['answer']) + else: + answers = [''] * len(questions) + assert len(questions) == len(answers) + + dlgs, pics_number = [], 0 + for i in range(len(questions)): + q, a = questions[i], answers[i] + if '' in q: + content = [] + tag_number = q.count('') + images = tgt_path[pics_number: pics_number + tag_number] + pics_number += tag_number + q_split = q.split('') + for i in range(tag_number): + qsp, im = q_split[i], images[i] + if qsp != '': + content.append(dict(type='text', value=qsp)) + content.append(dict(type='image', value=im)) + if q_split[-1] != '': + content.append(dict(type='text', value=q_split[-1])) + else: + content = [dict(type='text', value=q)] + dlgs.append(dict(role='user', content=content)) + assert '' not in a, 'We currently do not support images in the answer. ' + content = [dict(type='text', value=a)] + dlgs.append(dict(role='assistant', content=content)) + return dlgs + + +class MMDUDataset(ImageMTDataset): + + DATASET_URL = {'MMDU': 'https://opencompass.openxlab.space/utils/VLMEval/MMDU.tsv'} + DATASET_MD5 = {'MMDU': '848b635a88a078f49aebcc6e39792061'} + DIMS = [ + 'Creativity', 'Richness', 'Visual Perception', 'Logical Coherence', + 'Answer Accuracy', 'Image Relationship Understanding', 'Overall Score' + ] + + def calculat_metric(self, ans): + all = defaultdict(lambda: 0) + tot = defaultdict(lambda: 0) + valid = defaultdict(lambda: 0) + for k in ans: + res = ans[k]['res'] + assert isinstance(res, pd.DataFrame) + lt = len(res) + for i in range(lt): + line = res.iloc[i] + for k in self.DIMS: + tot[k] += 1 + if k in line and line[k] is not None: + try: + score = int(line[k]) + score = np.clip(score, 0, 10) + all[k] += score + valid[k] += 1 + except Exception as e: + print(f'Failed to parse the score: {str(e)}') + sp1 = {'set': 'all'} + sp1.update({k: all[k] / tot[k] * 10 for k in self.DIMS}) + sp2 = {'set': 'valid'} + sp2.update({k: all[k] / valid[k] * 10 for k in self.DIMS}) + + return pd.DataFrame([sp1, sp2]) + + def evaluate(self, eval_file, **judge_kwargs): + model = judge_kwargs['model'] + + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + score_file = get_intermediate_file_path(eval_file, f'_{model}_score', 'csv') + nproc = judge_kwargs.pop('nproc', 4) + + data = load(eval_file) + model = judge_kwargs.pop('model', 'gpt-4o') + judge_model = build_judge(model=model, **judge_kwargs) + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(judge_model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + from .utils.mmdu import mmdu_score + + if len(indices): + new_results = track_progress_rich( + mmdu_score, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file,) + ans = load(tmp_file) + for k, v in zip(indices, new_results): + assert k in ans + + metric = self.calculat_metric(ans) + dump(metric, score_file) + return metric diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/image_shortqa.py b/VLMEvalKit-sudoku/vlmeval/dataset/image_shortqa.py new file mode 100644 index 0000000000000000000000000000000000000000..0d60ded33503aaef56e8b07803c2abb83750685e --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/image_shortqa.py @@ -0,0 +1,163 @@ +from vlmeval import * +from .image_base import ImageBaseDataset +from .utils import build_judge +from .utils.multiple_choice import report_acc, eval_vanilla, eval_circular_group +from .utils.shortqa import ShortQA_prompt +from ..utils import track_progress_rich +from ..smp.file import get_intermediate_file_path + + +def ShortQA_auxeval(model, line): + def proc_str(s): + chs = set(s) + chs = [x for x in chs if x not in string.ascii_letters + ': '] + for ch in chs: + s = s.replace(ch, ' ') + return s + + def extraction(resp): + correct, reason = None, None + correct_st, correct_ed = '[Begin Correctness]', '[End Correctness]' + reason_st, reason_ed = '[Begin Reason]', '[End Reason]' + if correct_st in resp and correct_ed in resp: + correct = resp.split(correct_st)[1].split(correct_ed)[0].strip().lower() + if ('yes' in correct) ^ ('no' in correct): + correct = 1 if 'yes' in correct else 0 + if reason_st in resp and reason_ed in resp: + reason = resp.split(reason_st)[1].split(reason_ed)[0].strip() + return correct, reason + else: + return None, None + else: + return None, None + + prompt = ShortQA_prompt(line) + retry = 3 + for i in range(retry): + output = model.generate(prompt, temperature=0.5 * i) + ans = extraction(output) + # print(output, ans) + if ans[0] in [0, 1]: + return dict(hit=ans[0], log=ans[1]) + + return dict(hit=0, log='Fail to Judge') + + +def Comprehensive_auxeval(model, data): + def valid(record, key_name): + return key_name in record and (not pd.isna(record[key_name])) and record[key_name] != '' + + if isinstance(data, pd.DataFrame) and len(data) > 1: + # Should Adopt CircularEval + assert valid(data.iloc[0], 'A') + data['GT'] = data['answer'] + return eval_circular_group(model, data) + else: + item = data.iloc[0] if isinstance(data, pd.DataFrame) else data + if valid(item, 'A') and len(item['answer']) == 1: + item['GT'] = item['answer'] + return eval_vanilla(model, item) + else: + return ShortQA_auxeval(model, item) + + +class ImageShortQADataset(ImageBaseDataset): + TYPE = 'Short' + + DATASET_URL = { + 'LiveMMBench_Infographic': '', + 'LiveMMBench_Perception': '', + 'LiveMMBench_Reasoning': '', + 'LiveMMBench_Reasoning_circular': '', + 'hle':'https://opencompass.openxlab.space/utils/VLMEval/hle.tsv', + } + + DATASET_MD5 = { + 'hle': 'a83cbdbea89f27c2aa5b8f34a8894b72', + } + + def build_prompt(self, line): + msgs = super().build_prompt(line) + assert msgs[-1]['type'] == 'text' + msgs[-1]['value'] += '\nPlease directly provide a short answer to the question. ' + return msgs + + # It returns a DataFrame + def evaluate(self, eval_file, **judge_kwargs): + data = load(eval_file) + _ = self.dataset_name + assert 'answer' in data and 'prediction' in data + data['prediction'] = [str(x) for x in data['prediction']] + data['answer'] = [str(x) for x in data['answer']] + + storage = get_intermediate_file_path(eval_file, '_judge') + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(storage): + ans_map = {} if not osp.exists(tmp_file) else load(tmp_file) + + model = judge_kwargs.get('model', 'gpt-4o-mini') + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(model=model, **judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + model = None + warnings.warn('OPENAI_API_KEY is not working properly, will use exact matching for evaluation') + + if model is not None: + if 'g_index' not in data: + lines = [data.iloc[i] for i in range(len(data))] + indices = [x['index'] for x in lines if x['index'] not in ans_map] + lines = [x for x in lines if x['index'] not in ans_map] + tups = [(model, line) for line in lines] + else: + main_data = data[[x == y for x, y in zip(data['index'], data['g_index'])]] + lines = [data[data['g_index'] == x] for x in main_data['index']] + indices = [x.iloc[0]['g_index'] for x in lines if x.iloc[0]['g_index'] not in ans_map] + lines = [x for x in lines if x.iloc[0]['g_index'] not in ans_map] + tups = [(model, x) for x in lines] + data = main_data + + if len(lines): + res = track_progress_rich( + Comprehensive_auxeval, tups, nproc=nproc, chunksize=nproc, keys=indices, save=tmp_file) + for k, v in zip(indices, res): + ans_map[k] = v + + judge_results = [ans_map[x] for x in data['index']] + data['hit'] = [x['hit'] for x in judge_results] + data['log'] = [x['log'] for x in judge_results] + dump(data, storage) + + data = load(storage) + acc = report_acc(data) + + score_file = get_intermediate_file_path(eval_file, '_acc', 'csv') + dump(acc, score_file) + return acc + + +class PathVQA_VAL(ImageShortQADataset): + DATASET_URL = { + 'PathVQA_VAL': 'https://huggingface.co/datasets/Pfei111/PathVQA/resolve/main/PathVQA_VAL.tsv', + } + + DATASET_MD5 = { + 'PathVQA_VAL': None, + } + + +class PathVQA_TEST(ImageShortQADataset): + DATASET_URL = { + 'PathVQA_TEST': 'https://huggingface.co/datasets/Pfei111/PathVQA/resolve/main/PathVQA_TEST.tsv', + } + + DATASET_MD5 = { + 'PathVQA_TEST': None, + } diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/longvideobench.py b/VLMEvalKit-sudoku/vlmeval/dataset/longvideobench.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2ce0de21d7b924fb8d9a11d079c4d27af62bd0 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/longvideobench.py @@ -0,0 +1,335 @@ +from huggingface_hub import snapshot_download +from ..smp import * +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from glob import glob +import os + +FAIL_MSG = 'Failed to obtain answer via API.' + + +def timestamp_to_seconds(timestamp): + # Split the timestamp into hours, minutes, and seconds + h, m, s = timestamp.split(":") + # Convert hours, minutes, and total seconds (including fractions) to float and compute total seconds + total_seconds = int(h) * 3600 + int(m) * 60 + float(s) + return total_seconds + + +def uniformly_subsample(lst, K): + n = len(lst) + if K >= n: + return lst + step = n / K + return [lst[int(i * step)] for i in range(K)] + + +def insert_subtitles_into_frames( + frames, + frame_timestamps, + subtitles, + starting_timestamp_for_subtitles, + duration, +): + interleaved_list = [] + cur_i = 0 + + for subtitle in subtitles: + if "timestamp" in subtitle: + start, end = subtitle["timestamp"] + + if not isinstance(end, float): + end = duration + + start -= starting_timestamp_for_subtitles + end -= starting_timestamp_for_subtitles + + subtitle_timestamp = (start + end) / 2 + subtitle_text = subtitle["text"] + else: + start, end = subtitle["start"], subtitle["end"] + start = timestamp_to_seconds(start) + end = timestamp_to_seconds(end) + start -= starting_timestamp_for_subtitles + end -= starting_timestamp_for_subtitles + + subtitle_timestamp = (start + end) / 2 + subtitle_text = subtitle["line"] + + for i, (frame, frame_timestamp) in enumerate( + zip(frames[cur_i:], frame_timestamps[cur_i:]) + ): + if frame_timestamp <= subtitle_timestamp: + # print("frame:", frame_timestamp) + interleaved_list.append({"type": "image", "value": frame}) + cur_i += 1 + else: + break + + if end - start < 1: + end = subtitle_timestamp + 0.5 + start = subtitle_timestamp - 0.5 + + covering_frames = False + for frame, frame_timestamp in zip(frames, frame_timestamps): + if frame_timestamp < end and frame_timestamp > start: + covering_frames = True + break + + if covering_frames: + interleaved_list.append({"type": "text", "value": subtitle_text + "\n"}) + else: + pass + + for i, (frame, frame_timestamp) in enumerate( + zip(frames[cur_i:], frame_timestamps[cur_i:]) + ): + interleaved_list.append({"type": "image", "value": frame}) + return interleaved_list + + +class LongVideoBench(VideoBaseDataset): + + MD5 = '82905eae3a5ae7383c5a8ee9655e1ab9' + SYS = '' + + TYPE = 'Video-MCQ' + + def __init__(self, dataset='LongVideoBench', use_subtitle=False, nframe=0, fps=-1): + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + self.use_subtitle = use_subtitle + self.dataset_name = dataset + + @classmethod + def supported_datasets(cls): + return ['LongVideoBench'] + + def prepare_dataset(self, dataset_name='LongVideoBench', repo_id='longvideobench/LongVideoBench'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if not osp.exists(data_file): + return False + if md5(data_file) != self.MD5: + print("md5 mismatch", md5(data_file), self.MD5) + return False + data = load(data_file) + for video_pth in data['video_path']: + if not osp.exists(osp.join(pth, video_pth)): + print(video_pth, "is not found") + return False + return True + + if modelscope_flag_set(): + repo_id = "AI-ModelScope/LongVideoBench" + + cache_path = get_cache_path(repo_id) + + if cache_path is None: + cache_path = osp.expanduser("~/.cache/huggingface/hub/datasets--longvideobench--LongVideoBench") + if not osp.exists(cache_path): + os.makedirs(cache_path) + + if check_integrity(cache_path): + dataset_path = cache_path + else: + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if osp.exists(data_file) and md5(data_file) == self.MD5: + return + + data_file = pd.read_json(osp.join(pth, 'lvb_val.json')) + data_file = data_file.assign(index=range(len(data_file))) + data_file['video'] = data_file['video_id'] + data_file['video_path'] = data_file['video_path'].apply(lambda x: f'./videos/{x}') + + data_file.to_csv(osp.join(pth, f'{dataset_name}.tsv'), sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_snapshot_download(dataset_id=repo_id) + else: + snapshot_download(repo_id=repo_id, repo_type='dataset') + print("All videos are downloaded for LongVideoBench") + + if not glob(osp.join(cache_path, "videos")): + tar_files = glob(osp.join(cache_path, "**/*.tar*"), recursive=True) + + def untar_video_data(tar_file, cache_dir): + import tarfile + with tarfile.open(tar_file, "r") as tar_ref: + tar_ref.extractall(cache_dir) + print(f"Extracted all files from {tar_file} to {cache_dir}") + + def concat_tar_parts(tar_parts, output_tar): + with open(output_tar, "wb") as out_tar: + from tqdm import tqdm + for part in tqdm(sorted(tar_parts)): + with open(part, "rb") as part_file: + out_tar.write(part_file.read()) + print(f"Concatenated parts {tar_parts} into {output_tar}") + + tar_parts_dict = {} + + # Group tar parts together + for tar_file in tar_files: + base_name = tar_file.split(".tar")[0] + if base_name not in tar_parts_dict: + tar_parts_dict[base_name] = [] + tar_parts_dict[base_name].append(tar_file) + + # Concatenate and untar split parts + for base_name, parts in tar_parts_dict.items(): + print(f"Extracting following tar files: {parts}") + output_tar = base_name + ".tar" + if not osp.exists(output_tar): + print('Start concatenating tar files') + + concat_tar_parts(parts, output_tar) + print('Finish concatenating tar files') + + if not osp.exists(osp.join(cache_path, osp.basename(base_name))): + untar_video_data(output_tar, cache_path) + + print('All videos are extracted for LongVideoBench') + + dataset_path = cache_path + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + return dict(data_file=data_file, root=dataset_path) + + def save_video_frames(self, video_path, video_llm=False): + + vid_path = osp.join(self.data_root, video_path) + import decord + vid = decord.VideoReader(vid_path) + video_info = { + 'fps': vid.get_avg_fps(), + 'n_frames': len(vid), + } + if self.nframe > 0 and self.fps < 0: + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + frame_paths = self.frame_paths(video_path[:-4]) + elif self.fps > 0: + # not constrained by num_frames, get frames by fps + total_duration = video_info['n_frames'] / video_info['fps'] + required_frames = int(total_duration * self.fps) + step_size = video_info['fps'] / self.fps + indices = [int(i * step_size) for i in range(required_frames)] + frame_paths = self.frame_paths_fps(video_path[:-4], len(indices)) + + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.splitext(vid_path)[0] + '.lock' + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth) and not video_llm: + im.save(pth) + + return frame_paths, indices, video_info + + # def save_video_into_images(self, line, num_frames=8): + # frame_paths, indices, video_info = self.save_video_frames(line['video_path'], num_frames) + # return frame_paths + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + frames, indices, video_info = self.save_video_frames(line['video_path'], video_llm) + fps = video_info["fps"] + + message = [dict(type='text', value=self.SYS)] + if video_llm: + message.append(dict(type='video', value=osp.join(self.data_root, line['video_path']))) + else: + if not self.use_subtitle: + with open(osp.join(self.data_root, "subtitles", line["subtitle_path"])) as f: + subtitles = json.load(f) + + frame_message = insert_subtitles_into_frames( + frames, + [ind_ / fps for ind_ in indices], + subtitles, + line["starting_timestamp_for_subtitles"], + line["duration"] + ) + + message += frame_message + else: + for im in frames: + message.append(dict(type='image', value=im)) + + line['question'] += '\n' + '\n'.join( + ["{}. {}".format(chr(ord("A") + i), cand) for i, cand in enumerate(eval(line['candidates']))] + ) + prompt = line["question"] + "\nAnswer with the option's letter from the given choices directly." + message.append(dict(type='text', value=prompt)) + return message + + # It returns a dictionary + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + from .utils.longvideobench import get_dimension_rating, extract_characters_regex, extract_option + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, '_rating', 'json') + score_file = get_intermediate_file_path(eval_file, '_score') + + if not osp.exists(score_file): + model = judge_kwargs.get('model', 'exact_matching') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + data_un = data[~pd.isna(data['prediction'])] + + for idx in data['index']: + ans = data.loc[data['index'] == idx, 'correct_choice'].values[0] + ans = chr(ord("A") + ans) + pred = str(data.loc[data['index'] == idx, 'prediction'].values[0]) + + if extract_characters_regex(pred) == '': + extract_pred = extract_option( + model, + data.loc[data['index'] == idx].to_dict(orient='records')[0], + 'LongVideoBench' + ) + data.loc[idx, 'score'] = int(extract_pred == ans) + else: + data.loc[idx, 'score'] = int(extract_characters_regex(pred) == ans) + + rejected = [x for x in data['score'] if x == -1] + + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/mmalignbench.py b/VLMEvalKit-sudoku/vlmeval/dataset/mmalignbench.py new file mode 100644 index 0000000000000000000000000000000000000000..fd77deccd0876a1db7b5f792e41070f6bb8e6206 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/mmalignbench.py @@ -0,0 +1,298 @@ +# flake8: noqa +import re +from functools import partial + +from .image_base import ImageBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..smp import * +from ..utils import track_progress_rich + + +SYSTEM_PROMPT = """\ +Please act as an impartial evaluator and assess the quality of the responses provided by two AI assistants to a given user prompt and accompanying image. You will be provided with Assistant A's and Assistant B's answers. Your task is to determine which assistant's response is superior. + +Start your evaluation by generating your own answer to the prompt and image. Ensure that you complete your answer before reviewing any assistant responses. + +When evaluating the assistants' responses, compare each one to your own answer. + +First, assess whether the assistants' answers are helpful and relevant. A response is considered helpful if it appropriately addresses the prompt, follows the given instructions, and is well-organized. A relevant answer closely aligns with the context or requirements of the prompt. + +When applicable, consider the creativity and novelty of each assistant's response and evaluate the writing quality of both responses. + +Then, identify and correct any errors or inaccuracies in the assistants' answers. Lastly, identify any critical information missing from the assistants' responses that should have been included to improve the answer. + +After providing your explanation, you must output only one of the following choices as your final verdict with a label: + +1. Assistant A is significantly better: [[A>>B]] +2. Assistant A is slightly better: [[A>B]] +3. Tie, relatively the same: [[A=B]] +4. Assistant B is slightly better: [[B>A]] +5. Assistant B is significantly better: [[B>>A]] + +Example output: "My final verdict is tie: [[A=B]]".\ +""" + +SYSTEM_PROMPT_GT = """\ +Please act as an impartial evaluator and assess the quality of the responses provided by two AI assistants to a given user prompt and accompanying image. You will be provided with Assistant A's and Assistant B's answers. Your task is to determine which assistant's response is superior. + +Start your evaluation by generating your own answer to the prompt and image. Ensure that you complete your answer before reviewing any assistant responses. + +When evaluating the assistants' responses, compare each one to your own answer. + +First, assess whether the assistants' answers are helpful and relevant. A response is considered helpful if it appropriately addresses the prompt, follows the given instructions, and is well-organized. A relevant answer closely aligns with the context or requirements of the prompt. + +When applicable, consider the creativity and novelty of each assistant's response and evaluate the writing quality of both responses. + +Then, identify and correct any errors or inaccuracies in the assistants' answers. Lastly, identify any critical information missing from the assistants' responses that should have been included to improve the answer. Please refer to the provided Ground Truth answer, which constitutes the key fact relevant to the question. + +After providing your explanation, you must output only one of the following choices as your final verdict with a label: + +1. Assistant A is significantly better: [[A>>B]] +2. Assistant A is slightly better: [[A>B]] +3. Tie, relatively the same: [[A=B]] +4. Assistant B is slightly better: [[B>A]] +5. Assistant B is significantly better: [[B>>A]] + +Example output: "My final verdict is tie: [[A=B]]".\ +""" + +PROMPT_TEMPLATE = """**INPUT**: + +<|User Prompt|>\n{question} + +<|The Start of Assistant A's Answer|>\n{answer_1}\n<|The End of Assistant A's Answer|> + +<|The Start of Assistant B's Answer|>\n{answer_2}\n<|The End of Assistant B's Answer|> +""" + + +PROMPT_TEMPLATE_GT = """**INPUT**: + +<|User Prompt|>\n{question} + +<|Ground Truth|>\n{gt} + +<|The Start of Assistant A's Answer|>\n{answer_1}\n<|The End of Assistant A's Answer|> + +<|The Start of Assistant B's Answer|>\n{answer_2}\n<|The End of Assistant B's Answer|> +""" + + +REGEX_PATTERN = re.compile("\[\[([AB<>=]+)\]\]") # noqa: W605 + + +def get_score(judgement, pattern=REGEX_PATTERN): + matches = pattern.findall(judgement) + matches = [m for m in matches if m != ""] + if len(set(matches)) == 0: + return None, True + elif len(set(matches)) == 1: + return matches[0].strip("\n"), False + else: + return None, True + + +def MMAlignBench_auxeval(model, line): + if 'gt' in line and str(line['gt']) != 'nan': + config = dict(question=line['question'], gt=line['gt'], answer_1=line['A'], answer_2=line['B']) + prompt = SYSTEM_PROMPT_GT + '\n' + PROMPT_TEMPLATE_GT.format(**config) + # prompt = PROMPT_TEMPLATE.format(**config) + print('gt_prompt'+prompt) + else: + config = dict(question=line['question'], answer_1=line['A'], answer_2=line['B']) + prompt = SYSTEM_PROMPT + '\n' + PROMPT_TEMPLATE.format(**config) + # prompt = PROMPT_TEMPLATE.format(**config) + print('prompt'+prompt) + + prefix = 'data:image/jpeg;base64,' + img = prefix + line['image'] + + messages = [ + dict(type='text', value=prompt), + dict(type='image', value=img) + ] + + retry = 2 + while retry: + resp = model.generate(messages) + score, try_again = get_score(resp) + if not try_again: + break + retry -= 1 + + if score is None: + return 'Unknown' + return [score, resp] + + +class MMAlignBench(ImageBaseDataset): + TYPE = 'VQA' + DATASET_URL = {'MMAlignBench': 'https://opencompass.openxlab.space/utils/VLMEval/MMAlignBench.tsv'} + DATASET_MD5 = {'MMAlignBench': 'd00d8e61c99257cbaf76d8d5e926f01e'} + + score_map = { + 'A>>B': -2, + 'A>B': -1, + 'A=B': 0, + 'B>A': 1, + 'B>>A': 2 + } + + # Given one data record, return the built prompt (a multi-modal message), can override + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + + if self.meta_only: + tgt_path = toliststr(line['image_path']) + else: + tgt_path = self.dump_image(line) + + question = line['question'] + + msgs = [] + if isinstance(tgt_path, list): + msgs.extend([dict(type='image', value=p) for p in tgt_path]) + else: + msgs = [dict(type='image', value=tgt_path)] + # WildVision adopts text first + msgs = [dict(type='text', value=question)] + msgs + return msgs + + @classmethod + def gen_eval_base(self, eval_file, b64_map): + data = load(eval_file) + data['B'] = data.pop('prediction') + data['A'] = data.pop('claude3_sonnet') + data['image'] = [b64_map[x] for x in data['index']] + return data + + # It returns a DataFrame + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + # We adopt pairwise evaluation (twice for a pair) for this dataset + model = judge_kwargs['model'] + storage = get_intermediate_file_path(eval_file, f'_{model}') + score_file = get_intermediate_file_path(eval_file, f'_{model}_score', 'csv') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(storage): + raw_data = MMAlignBench('MMAlignBench').data + b64_map = {x: y for x, y in zip(raw_data['index'], raw_data['image'])} + data = self.gen_eval_base(eval_file, b64_map) + + # judge_kwargs['system_prompt'] = SYSTEM_PROMPT + judge_kwargs['temperature'] = 0 + judge_kwargs['img_detail'] = 'high' + judge_kwargs['timeout'] = 300 + model = build_judge(max_tokens=4096, **judge_kwargs) + + assert model.working(), ( + 'MMAlignBench evaluation requires a working OPENAI API\n' + DEBUG_MESSAGE + ) + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = load(tmp_file) if osp.exists(tmp_file) else {} + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + new_results = track_progress_rich( + MMAlignBench_auxeval, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file, + ) + ans = load(tmp_file) + for k, v in zip(indices, new_results): + ans[k] = {'score': v[0], 'resp': v[1]} + else: + for k,v in ans.items(): + ans[k] = {'score': v[0], 'resp': v[1]} + # breakpoint() + data['score'] = [ans[x]['score'] for x in data['index']] + data['judge'] = [ans[x]['resp'] for x in data['index']] + data.pop('image') + dump(data, storage) + + data = load(storage) + lt = len(data) + + scores = defaultdict(lambda: 0) + type_scores = defaultdict(lambda: defaultdict(lambda: 0)) + + for i in range(lt): + item = data.iloc[i] + if item['score'] not in self.score_map: + score = 0 + else: + score = self.score_map[item['score']] + if '_rev' in item['index']: + score = -score + scores[score] += 1 + type = item['type'] + type_scores[type][score] += 1 + + name_map = { + 2: 'Much Better', + 1: 'Better', + 0: 'Tie', + -1: 'Worse', + -2: 'Much Worse' + } + scores = {name_map[k]: v for k, v in scores.items()} + scores['Reward'] = ( + 100 * scores.get('Much Better', 0) + + 50 * scores.get('Better', 0) + - 50 * scores.get('Worse', 0) + - 100 * scores.get('Much Worse', 0) + ) / lt + scores['Win Rate'] = (scores.get('Better', 0) + scores.get('Much Better', 0)) / lt + scores = {k: [v] for k, v in scores.items()} + scores = pd.DataFrame(scores) + + for type_name, type_score_dict in type_scores.items(): + type_score_dict = {name_map[k]: v for k, v in type_score_dict.items()} + type_lt = sum(type_score_dict.values()) + + type_score_dict['Reward'] = ( + ( + 100 * type_score_dict.get('Much Better', 0) + + 50 * type_score_dict.get('Better', 0) + - 50 * type_score_dict.get('Worse', 0) + - 100 * type_score_dict.get('Much Worse', 0) + ) + / type_lt + if type_lt > 0 + else 0 + ) + + type_score_dict['Win Rate'] = ( + (type_score_dict.get('Better', 0) + type_score_dict.get('Much Better', 0)) / type_lt + if type_lt > 0 + else 0 + ) + + # 将该类型的得分添加到结果中 + type_score_df = pd.DataFrame( + { + f"{type_name}_Much Better": [type_score_dict.get('Much Better', 0)], + f"{type_name}_Better": [type_score_dict.get('Better', 0)], + f"{type_name}_Tie": [type_score_dict.get('Tie', 0)], + f"{type_name}_Worse": [type_score_dict.get('Worse', 0)], + f"{type_name}_Much Worse": [type_score_dict.get('Much Worse', 0)], + f"{type_name}_Reward": [type_score_dict['Reward']], + f"{type_name}_Win Rate": [type_score_dict['Win Rate']], + } + ) + scores = pd.concat([scores, type_score_df], axis=1) + + dump(scores, score_file) + return scores diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/mmlongbench.py b/VLMEvalKit-sudoku/vlmeval/dataset/mmlongbench.py new file mode 100644 index 0000000000000000000000000000000000000000..3379d6af657f99ff352a860a49c63b74393f509f --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/mmlongbench.py @@ -0,0 +1,584 @@ +import re +import math +from urllib.request import urlopen +from PIL import Image, ImageDraw, ImageFont +import torchvision.transforms as transforms + +from vlmeval.dataset.utils import build_judge, levenshtein_distance +from vlmeval.smp import * +from .image_base import ImageBaseDataset +from ..smp.file import get_intermediate_file_path + +FAIL_MSG = 'Failed to obtain answer via API.' + + +def get_gpt4_ICE(): + example_1 = """ +--- +Question: List the primary questions asked about the services in this report. +Analysis: The primary questions asked about the services in the report for The Limes Residential Home are:\n\n +1. Is the service safe?\n +2. Is the service effective?\n +3. Is the service caring?\n +4. Is the service responsive?\n +5. Is the service well-led? +Extracted answer: [ + 'Is the servife safe?', + 'Is the service effective', + 'Is the serve caring?', + 'Is the service responsive?', + 'Is the service well-led?' +] +Answer format: List\n +""" + + example_2 = """ +--- +Question: How many regulations of the HSCA 2008 are breached in all according to this report? +Analysis: According to the report, the provider breached 10 Health and Social Care Act 2008 (Regulated Activities) +Regulations in total. Here are the specifics:\n\n1. Regulation 13: Safeguarding service users from abuse and +improper treatment\n2. Regulation 12: Safe care and treatment\n3. Regulation 18: Staffing\n4. Regulation 11: +Need for consent\n5. Regulation 10: Dignity and respect\n6. Regulation 9: Person-centred care\n7. Regulation 17: +Good governance\n8. Regulation 18 (CQC Registration Regulations 2009): Notification of other incidents\n9. +Regulation 18: Failure to maintain an accurate and up-to-date care plan\n10. Regulation 11: Failure to implement +the Mental Capacity Act 2005 code of practice effectively\n\nThese breaches involve issues concerning staffing, +safeguarding, medicines management, dignity and respect, consent, care planning, governance, and failure to +notify the CQC of incidents. +Extracted answer: 10 +Answer format: Integer\n +""" + + example_3 = """ +--- +Question: According to the survey that is the percentage of Chinese who are paying more or +about the same attention to politics after Trump's election? +Analysis: The survey provided does not specify the percentage of Chinese individuals specifically who are paying +more or about the same attention to politics after Trump's election. The report focuses primarily on American +demographics and does not include specific details about the Chinese population in relation to this question. If +you need information about a different demographic or a summary of the findings from the American demographic, +I can certainly help with that! +Extracted answer: Not answerable +Answer format: String\n +""" + + example_4 = """ +--- +Question: How many quotations from male respondent over 50 years old are included in this report? +Analysis: The image you've provided appears to be a screenshot of a document with multiple charts. However, the +text is too small and blurry to read accurately. If you can provide a clearer image or more context, I might be +able to help you with your question. +Extracted answer: Fail to answer +Answer format: String\n +""" + + return [example_1, example_2, example_3, example_4] + + +def build_mmlongbench_gpt4_prompt(line): + task_description = """ +Given the question and analysis, you are tasked to extract answers with required formats from the free-form analysis. +- Your extracted answers should be one of the following formats: (1) Integer, (2) Float, (3) String and (4) List. +If you find the analysis the question can not be answered from the given documents, type "Not answerable". +Exception: If the analysis only tells you that it can not read/understand the images or documents, +type "Fail to answer". +- Please make your response as concise as possible. Also note that your response should be formatted as below: +``` +Extracted answer: [answer] +Answer format: [answer format] +``` +Please read the following example, then extract the answer from the model response +and type it at the end of the prompt.\n +""" + question = line['question'] + prediction = str(line['prediction']) + prompt = task_description + examples = get_gpt4_ICE() + for example in examples: + prompt += example + prompt += '---\nQuestion:' + question + '\n' + prompt += 'Analysis: ' + prediction + return prompt + + +def anls_compute(groundtruth, prediction, threshold=0.5): + dist = levenshtein_distance(groundtruth, prediction) + length = max(len(groundtruth.upper()), len(prediction.upper())) + value = 0.0 if length == 0 else float(dist) / float(length) + anls = 1.0 - value + if anls <= threshold: + anls = 0.0 + return anls + + +def is_float_equal(reference, prediction, include_percentage: bool = False, is_close: float = False) -> bool: + def get_precision(gt_ans: float) -> int: + precision = 3 + if '.' in str(gt_ans): + precision = len(str(gt_ans).split('.')[-1]) + return precision + + reference = float(str(reference).strip().rstrip('%').strip()) + try: + prediction = float(str(prediction).strip().rstrip('%').strip()) + except: + return False + + if include_percentage: + gt_result = [reference / 100, reference, reference * 100] + else: + gt_result = [reference] + for item in gt_result: + try: + if is_close: + if math.isclose(item, prediction, rel_tol=0.01): + return True + precision = max(min(get_precision(prediction), get_precision(item)), 2) + if round(prediction, precision) == round(item, precision): + return True + except Exception: + continue + return False + + +def get_clean_string(s): + s = str(s).lower().strip() + if s.endswith('mile'): + s.rstrip('mile').strip() + if s.endswith('miles'): + s.rstrip('miles').strip() + if s.endswith('million'): + s.rstrip('million').strip() + # remove parenthesis + s = re.sub(r'\s*\([^)]*\)', '', s).strip() + # remove quotes + s = re.sub(r"^['\"]|['\"]$", '', s).strip() + s = s.strip().lstrip('$').strip() + s = s.strip().rstrip('%').strip() + return s + + +def is_exact_match(s): + flag = False + # Website + if 'https://' in s: + flag = True + # code file + if s.endswith('.py') or s.endswith('ipynb'): + flag = True + if s.startswith('page'): + flag = True + # telephone number + if re.fullmatch(r'\b\d+(-\d+|\s\d+)?\b', s): + flag = True + # time + if 'a.m.' in s or 'p.m.' in s: + flag = True + # YYYY-MM-DD + if re.fullmatch(r'\b\d{4}[-\s]\d{2}[-\s]\d{2}\b', s): + flag = True + # YYYY-MM + if re.fullmatch(r'\b\d{4}[-\s]\d{2}\b', s): + flag = True + # Email address + if re.fullmatch(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', s): + flag = True + return flag + + +def isfloat(num): + try: + float(num) + return True + except ValueError: + return False + + +def get_font(): + try: + truetype_url = "http://opencompass.openxlab.space/utils/Fonts/SimHei.ttf" + ff = urlopen(truetype_url) + font = ImageFont.truetype(ff, size=40) + except Exception as e: + logging.warning(f'{type(e)}: {e}') + logging.warning("Fail to download the font. Use the default one.") + font = ImageFont.load_default(size=40) + return font + + +def frame2img(img_path_list, font, save_path=None, idx_start=0): + imgs = [Image.open(img_path) for img_path in img_path_list] + + new_imgs = [] + for img in imgs: + w, h = img.size + scale = w / h + if w > h: + new_w = 560 * 2 + new_h = int(560 * 2 / scale) + else: + new_w = int(560 * 2 * scale) + new_h = 560 * 2 + img = transforms.functional.resize(img, [new_h, new_w],) + new_imgs.append(img) + imgs = new_imgs + new_w = 0 + new_h = 0 + pad = 40 + if w > h: + for im in imgs: + w, h = im.size + new_w = max(new_w, w) + new_h += h + 10 + pad + new_img = Image.new("RGB", (new_w, new_h), "white") + draw = ImageDraw.Draw(new_img) + curr_h = 0 + for idx, im in enumerate(imgs): + w, h = im.size + new_img.paste(im, (0, pad + curr_h)) + draw.text((0, curr_h), f"", font=font, fill="black") + if idx + 1 < len(imgs): + draw.line([(0, pad + curr_h + h + 5), (new_w, pad + curr_h + h + 5)], fill='black', width=2) + curr_h += h + 10 + pad + else: + for im in imgs: + w, h = im.size + new_w += w + 10 + new_h = max(new_h, h) + new_h += pad + new_img = Image.new('RGB', (new_w, new_h), 'white') + draw = ImageDraw.Draw(new_img) + curr_w = 0 + for idx, im in enumerate(imgs): + w, h = im.size + new_img.paste(im, (curr_w, pad)) + draw.text((curr_w, 0), f"", font=font, fill='black') + if idx + 1 < len(imgs): + draw.line([(curr_w + w + 5, 0), (curr_w + w + 5, new_h)], fill='black', width=2) + curr_w += w + 10 + + if save_path is not None: + new_img.save(save_path) + + return new_img + + +def concat_images(image_list, max_concat=1, column_num=1): + concatenated_images = [] + if column_num == -1: + MAX_COLUMN_NUM = 20 + max_concat = 1 + while len(image_list) / max_concat > MAX_COLUMN_NUM: + max_concat += 1 + interval = max(math.ceil(len(image_list) / max_concat), 1) + for i in range(0, len(image_list), interval): + batch_images = image_list[i:i + interval] + concatenated_image = frame2img(batch_images, font=get_font(), idx_start=i) + concatenated_images.append(concatenated_image) + else: + interval = max(math.ceil(len(image_list) / max_concat), 1) + for i in range(0, len(image_list), interval): + batch_images = [Image.open(filename) for filename in image_list[i:i + interval]] + if column_num == 1: + total_height = batch_images[0].height * len(batch_images) + else: + total_height = batch_images[0].height * ((len(batch_images) - 1) // column_num + 1) + concatenated_image = Image.new('RGB', (batch_images[0].width * column_num, total_height), 'white') + + x_offset, y_offset = 0, 0 + for count, image in enumerate(batch_images): + concatenated_image.paste(image, (x_offset, y_offset)) + x_offset += image.width + if (count + 1) % column_num == 0: + y_offset += image.height + x_offset = 0 + concatenated_images.append(concatenated_image) + return concatenated_images + + +def eval_score(gt, pred, answer_type): + if answer_type == 'Int': + try: + gt, pred = int(gt), int(float(pred)) + except: + pred = '' + score = (gt == pred) + elif answer_type == 'Float': + try: + gt = float(get_clean_string(str(gt))) + pred = float(get_clean_string(str(pred))) + except: + pred = '' + score = is_float_equal(gt, pred, include_percentage=True, is_close=True) + elif answer_type == 'Str': + gt = get_clean_string(gt) + pred = get_clean_string(pred) + if is_exact_match(gt): + score = (gt == pred) + else: + score = anls_compute(gt, pred) + else: + if isinstance(gt, str) and gt.startswith('['): + gt = eval(gt) + if not isinstance(gt, list): + gt = [gt] + if isinstance(pred, str) and pred.startswith('['): + pred = eval(pred) + if not isinstance(pred, list): + pred = [pred] + print(len(gt), len(pred)) + if len(gt) != len(pred): + score = 0.0 + else: + gt = sorted([get_clean_string(a) for a in gt]) + pred = sorted([get_clean_string(a) for a in pred]) + print(gt, pred) + if isfloat(gt[0]) or is_exact_match(gt[0]): + score = ('-'.join(gt) == '-'.join(pred)) + else: + score = min([anls_compute(gt_v, pred_v) for gt_v, pred_v in zip(gt, pred)]) + + return float(score) + + +def MMLongBench_auxeval(model, line): + prompt = build_mmlongbench_gpt4_prompt(line) + log = '' + retry = 5 + + for i in range(retry): + prediction = line['prediction'] + res = model.generate(prompt, temperature=i * 0.5) + + if FAIL_MSG in res: + log += f'Try {i}: output is {prediction}, failed to parse.\n' + else: + log += 'Succeed' + try: + pred = res.split('Answer format:')[0].split('Extracted answer:')[1].strip() + except: + pred = '' + return dict(log=log, res=res, pred=pred) + log += 'All 5 retries failed.\n' + return dict(log=log, res='', pred='') + + +def get_f1(data): + gt_pos_data = data[data.apply(lambda k: k['answer'] != 'Not answerable', axis=1)] + pred_pos_data = data[data.apply(lambda k: k['pred'] != 'Not answerable', axis=1)] + recall = sum(gt_pos_data['score'].tolist()) / len(gt_pos_data) + precision = sum(pred_pos_data['score'].tolist()) / len(pred_pos_data) + return 2 * recall * precision / (recall + precision) + + +def MMLongBench_acc(result_file): + data = load(result_file) + overall_score = 0.0 + score_list = list() + for i in range(len(data)): + item = data.iloc[i] + try: + score = eval_score(item['answer'], item['pred'], item['answer_format']) + except: + score = 0.0 + score_list.append(score) + overall_score += score + + data['score'] = score_list + dump(data, result_file) + + data_chart = data[data.apply(lambda k: 'Chart' in eval(k['evidence_sources']), axis=1)] + data_table = data[data.apply(lambda k: 'Table' in eval(k['evidence_sources']), axis=1)] + data_image = data[data.apply(lambda k: 'Figure' in eval(k['evidence_sources']), axis=1)] + data_text = data[data.apply(lambda k: 'Pure-text (Plain-text)' in eval(k['evidence_sources']), axis=1)] + data_layout = data[data.apply(lambda k: 'Generalized-text (Layout)' in eval(k['evidence_sources']), axis=1)] + + data_single = data[data.apply(lambda k: len(eval(k['evidence_pages'])) == 1, axis=1)] + data_multi = data[data.apply(lambda k: len(eval(k['evidence_pages'])) > 1, axis=1)] + data_unans = data[data.apply(lambda k: len(eval(k['evidence_pages'])) == 0, axis=1)] + + res = dict() + res['category'] = [ + 'overall_f1', 'overall_acc', 'text', 'layout', 'table', 'chart', + 'image', 'single-page', 'multi-page', 'unanswerable' + ] + res['num'] = [ + len(data), len(data), len(data_text), len(data_layout), len(data_table), + len(data_chart), len(data_image), len(data_single), len(data_multi), len(data_unans) + ] + res['avg_score'] = [ + get_f1(data), + overall_score / len(data), + sum(data_text['score'].tolist()) / len(data_text) if len(data_text) > 0 else 0.0, + sum(data_layout['score'].tolist()) / len(data_layout) if len(data_layout) > 0 else 0.0, + sum(data_table['score'].tolist()) / len(data_table) if len(data_table) > 0 else 0.0, + sum(data_chart['score'].tolist()) / len(data_chart) if len(data_chart) > 0 else 0.0, + sum(data_image['score'].tolist()) / len(data_image) if len(data_image) > 0 else 0.0, + sum(data_single['score'].tolist()) / len(data_single) if len(data_single) > 0 else 0.0, + sum(data_multi['score'].tolist()) / len(data_multi) if len(data_multi) > 0 else 0.0, + sum(data_unans['score'].tolist()) / len(data_unans) if len(data_unans) > 0 else 0.0, + ] + res = pd.DataFrame(res) + return res + + +class MMLongBench(ImageBaseDataset): + + TYPE = 'VQA' + + DATASET_URL = { + 'MMLongBench_DOC': 'https://opencompass.openxlab.space/utils/VLMEval/MMLongBench_DOC.tsv', + } + DATASET_MD5 = { + 'MMLongBench_DOC': '9b393e1f4c52718380d50586197eac9b', + } + + SUPPORTED_MODELS = { + 'GPT4': (1, 1), + 'GPT4V': (1, 1), + 'GPT4V_HIGH': (1, 1), + 'GPT4o': (1, 1), + 'GPT4o_HIGH': (1, 1), + 'GPT4o_MINI': (1, 1), + 'MiniCPM-Llama3-V-2_5': (1, 5), + 'InternVL-Chat-V1-5': (5, 2), + 'XComposer2_4KHD': (1, 5), + 'XComposer2d5': (1, -1), + } + + def __init__(self, dataset, **kwargs): + self.model_list = list(self.SUPPORTED_MODELS.keys()) + model_name = kwargs['model'] + if not listinstr(self.model_list, model_name): + raise AssertionError("{} doesn't support the evaluation on MMLongBench_DOC.".format(model_name)) + super(MMLongBench, self).__init__(dataset) + + self.is_api = True if listinstr(['GPT4'], model_name) else False + self.max_pages = 120 + concat_num, column_num = self.SUPPORTED_MODELS.get(model_name) + self.concat_num = concat_num + self.column_num = column_num + + def dump_image(self, origin_line): + os.makedirs(self.img_root, exist_ok=True) + try: + import fitz + except Exception as e: + logging.critical(f'{type(e)}: {e}') + logging.critical('Please use `pip install pymupdf` to parse PDF files.') + + line = origin_line.copy() + line['image_path'] = line['image_path'][:self.max_pages] + skip_pdf_parse = True + for im_name in line['image_path']: + path = osp.join(self.img_root, im_name) + if not read_ok(path): + skip_pdf_parse = False + break + + # Just for being compatible with the zooped loop: zip(line['image'], line['image_path']) + if skip_pdf_parse: + line['image'] = line['image_path'] + else: + pdf_data = base64.b64decode(line['image']) + pdf_file = io.BytesIO(pdf_data) + encoded_images = [] + with fitz.open(stream=pdf_file, filetype='pdf') as doc: + doc = doc[:self.max_pages] + for page in doc: + image = page.get_pixmap(dpi=144) + image_file = io.BytesIO(image.tobytes(output='png')) + image = Image.open(image_file) + encoded_image = encode_image_to_base64(image) + encoded_images.append(encoded_image) + line['image'] = encoded_images + print('process {}'.format(line['doc_id'])) + + if 'image' in line: + if isinstance(line['image'], list): + tgt_path = [] + assert 'image_path' in line + for img, im_name in zip(line['image'], line['image_path']): + path = osp.join(self.img_root, im_name) + if not read_ok(path): + decode_base64_to_image_file(img, path) + tgt_path.append(path) + else: + tgt_path = osp.join(self.img_root, f"{line['index']}.jpg") + if not read_ok(tgt_path): + decode_base64_to_image_file(line['image'], tgt_path) + tgt_path = [tgt_path] + else: + assert 'image_path' in line + tgt_path = toliststr(line['image_path']) + + if self.concat_num > 0 and not self.is_api: + concatenated_images = concat_images(tgt_path, max_concat=self.concat_num, column_num=self.column_num) + + old_tgt_path = tgt_path + assert isinstance(old_tgt_path, list) + if self.column_num != -1: + tgt_path = [ + '_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat{}_{}.jpg'.format(self.concat_num, i) + for i in range(len(concatenated_images)) + ] + else: + tgt_path = [ + '_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat_all_{}.jpg'.format(i) + for i in range(len(concatenated_images)) + ] + + for path, concatenated_image in zip(tgt_path, concatenated_images): + if not read_ok(path): + decode_base64_to_image_file(encode_image_to_base64(concatenated_image), path) + num_images, image_size = len(old_tgt_path), concatenated_image.size + print('concat {} images to a new one with size {}. save at {}'.format(num_images, image_size, path)) + return tgt_path + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + logger = get_logger('Evaluation') + model = judge_kwargs['model'] + + storage = get_intermediate_file_path(eval_file, f'_{model}') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + + if osp.exists(storage): + logger.warning(f'GPT scoring file {storage} already exists, will reuse it in MMLongBench_eval. ') + else: + data = load(eval_file) + model = build_judge(max_tokens=128, **judge_kwargs) + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + new_results = list() + for model, line in tqdm(tups): + res = MMLongBench_auxeval(model, line) + new_results.append(res) + + log_map, res_map, pred_map = {}, {}, {} + all_inds = [line['index'] for line in lines] + for k, v in zip(all_inds, new_results): + log_map[k] = v['log'] + res_map[k] = v['res'] + pred_map[k] = v['pred'] + data['res'] = [res_map[idx] for idx in data['index']] + data['log'] = [log_map[idx] for idx in data['index']] + data['pred'] = [pred_map[idx] for idx in data['index']] + dump(data, storage) + + score = MMLongBench_acc(storage) + score_pth = get_intermediate_file_path(storage, '_score', 'csv') + + dump(score, score_pth) + logger.info(f'MMLongBench_eval successfully finished evaluating {eval_file}, results saved in {score_pth}') + logger.info('Score: ') + logger.info(score) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/moviechat1k.py b/VLMEvalKit-sudoku/vlmeval/dataset/moviechat1k.py new file mode 100644 index 0000000000000000000000000000000000000000..fed87753663c1a2cc5a75193998ffffac0ec78d1 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/moviechat1k.py @@ -0,0 +1,264 @@ +from huggingface_hub import snapshot_download +from ..smp import * +from ..smp.file import get_intermediate_file_path, get_file_extension +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..utils import track_progress_rich +import random +import json +import ast +from glob import glob + +FAIL_MSG = 'Failed to obtain answer via API.' + + +class MovieChat1k(VideoBaseDataset): + + MD5 = '7c0aa7e10de1cddb37af42b4abc9a2dd' + + TYPE = 'Video-VQA' + + def __init__(self, dataset='MovieChat1k', pack=False, nframe=0, fps=-1, subset='all', limit=1.0): + super().__init__(dataset=dataset, pack=pack, nframe=nframe, fps=fps) + + if subset == 'all': + pass + elif subset == 'global': + self.data = self.data[self.data['mode'] == 'global'] + elif subset == 'breakpoint': + self.data = self.data[self.data['mode'] == 'breakpoint'] + else: + raise ValueError(f'Invalid subset: {subset}') + + if limit <= 1.0 and limit > 0: + sample_num = int(limit * len(self.data)) + self.data = self.data.iloc[:sample_num] + elif limit > 1.0 and limit < len(self.data): + self.data = self.data.iloc[:limit] + else: + raise ValueError(f'Invalid limit: {limit}') + + @classmethod + def supported_datasets(cls): + return ['MovieChat1k'] + + def prepare_dataset(self, dataset_name='MovieChat1k', repo_id='Enxin/VLMEval-MovieChat1k'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if md5(data_file) != self.MD5: + return False + data = load(data_file) + for video_pth in data['video']: + if not osp.exists(osp.join(pth, video_pth)): + return False + return True + + if os.path.exists(repo_id): + dataset_path = repo_id + else: + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + cache_path = snapshot_download(repo_id=repo_id, repo_type="dataset") + if not glob(osp.join(cache_path, "video")): + tar_files = glob(osp.join(cache_path, "**/*.tar*"), recursive=True) + + def untar_video_data(tar_file, cache_dir): + import tarfile + with tarfile.open(tar_file, "r") as tar_ref: + tar_ref.extractall(cache_dir) + print(f"Extracted all files from {tar_file} to {cache_dir}") + + def concat_tar_parts(tar_parts, output_tar): + with open(output_tar, "wb") as out_tar: + from tqdm import tqdm + for part in tqdm(sorted(tar_parts)): + with open(part, "rb") as part_file: + out_tar.write(part_file.read()) + print(f"Concatenated parts {tar_parts} into {output_tar}") + + tar_parts_dict = {} + + # Group tar parts together + for tar_file in tar_files: + base_name = tar_file.split(".tar")[0] + if base_name not in tar_parts_dict: + tar_parts_dict[base_name] = [] + tar_parts_dict[base_name].append(tar_file) + + # Concatenate and untar split parts + for base_name, parts in tar_parts_dict.items(): + print(f"Extracting following tar files: {parts}") + output_tar = base_name + ".tar" + if not osp.exists(output_tar): + print('Start concatenating tar files') + + concat_tar_parts(parts, output_tar) + print('Finish concatenating tar files') + + if not osp.exists(osp.join(cache_path, 'videos')): + untar_video_data(output_tar, cache_path) + dataset_path = cache_path + self.video_path = osp.join(dataset_path, 'videos/') + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + return dict(data_file=data_file, root=osp.join(dataset_path, 'videos')) + + def build_prompt_pack(self, line): + if isinstance(line, int): + assert line < len(self) + video = self.videos[line] + elif isinstance(line, pd.Series): + video = line['video'] + elif isinstance(line, str): + video = line + + frames = self.save_video_frames(video) + message = [] + for im in frames: + message.append(dict(type='image', value=im)) + + message.append(dict(type='text', value=line['question'], role='user')) + return message + + def build_prompt_nopack(self, line, video_llm): + """Build prompt for a single line without packing""" + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + if video_llm: + video_path = os.path.join(self.video_path, line['video']) + return [ + dict(type='video', value=video_path), + dict(type='text', value=line['question']) + ] + else: + frames = self.save_video_frames(line['video']) + message = [] + for im in frames: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=line['question'])) + return message + + def build_prompt(self, line, video_llm): + if self.pack and not video_llm: + return self.build_prompt_pack(line) + else: + return self.build_prompt_nopack(line, video_llm) + + @staticmethod + def remove_side_quote(s, syms=[',', '"', "'"]): + if np.all([x in syms for x in s]): + return '' + while s[0] in syms: + s = s[1:] + while s[-1] in syms: + s = s[:-1] + return s + + @staticmethod + def robust_json_load(s): + try: + jsons = list(extract_json_objects(s)) + assert len(jsons) == 1 + return jsons[0] + except: + if '{' in s and s.find('{') == s.rfind('{'): + sub_str = s[s.find('{') + 1:].strip() + lines = sub_str.split('\n') + res = {} + for l in lines: + l = l.strip() + if ': ' in l: + key = l.split(': ')[0].strip() + val = l.split(': ')[1].strip() + key = MovieChat1k.remove_side_quote(key) + val = MovieChat1k.remove_side_quote(val) + if len(key) and len(val): + res[key] = val + return res + return None + + def load_pack_answers(self, data_raw): + vstats = defaultdict(lambda: 0) + data = defaultdict(lambda: {}) + + for k in data_raw: + ans = data_raw[k].strip() + if FAIL_MSG in ans: + vstats['GEN_FAIL'] += 1 + continue + res = self.robust_json_load(ans) + if res is not None: + data[k] = res + vstats['PARSE_OK'] += 1 + else: + vstats['PARSE_FAIL'] += 1 + + # return data + meta = cp.deepcopy(self.data) + lt = len(meta) + prediction = [] + for i in range(lt): + line = meta.iloc[i] + vid = line['video'] + idx = str(line['index']) + prediction.append(data[vid][idx] if idx in data[vid] else None) + meta['prediction'] = prediction + vstats['VALIDQ'] = len([x for x in prediction if x is not None]) + vstats['INVALIDQ'] = len([x for x in prediction if x is None]) + return meta, vstats + + # It returns a dictionary + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + from .utils.moviechat1k import get_dimension_rating, prepare_score_prompt + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + judge = judge_kwargs.setdefault('model', 'chatgpt-0125') + assert judge in ['chatgpt-0125'], f'Invalid judge model for MovieChat1k: {judge}' + nproc = judge_kwargs.pop('nproc', 4) + _ = judge_kwargs.pop('verbose', None) + _ = judge_kwargs.pop('retry', None) + + tmp_file = get_intermediate_file_path(eval_file, f'_{judge}_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, f'_{judge}_rating', 'json') + score_file = get_intermediate_file_path(eval_file, f'_{judge}_score') + + model = build_judge(**judge_kwargs) + + if not osp.exists(score_file): + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if model.fail_msg not in v} + + data = load(eval_file) + data_un = data[~data['index'].isin(res)] + data_un = data_un[~pd.isna(data_un['prediction'])] + lt = len(data_un) + prompts = [prepare_score_prompt(data_un.iloc[i]) for i in range(lt)] + indices = [data_un.iloc[i]['index'] for i in range(lt)] + if len(prompts): + _ = track_progress_rich( + model.generate, + prompts, + keys=indices, + save=tmp_file, + nproc=nproc, + chunksize=nproc + ) + score_map = load(tmp_file) + data['score'] = [score_map[idx] if idx in score_map else -1 for idx in data['index']] + rejected = [x for x in score_map.values() if FAIL_MSG in x] + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(score_map)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as 0 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/mvbench.py b/VLMEvalKit-sudoku/vlmeval/dataset/mvbench.py new file mode 100644 index 0000000000000000000000000000000000000000..69a49c0af24eba7f8238db372b127db0f6aa8f50 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/mvbench.py @@ -0,0 +1,675 @@ +import huggingface_hub +from huggingface_hub import snapshot_download +from ..smp import * +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..utils import track_progress_rich +import torchvision.transforms as T +from torchvision import transforms +from torchvision.transforms.functional import InterpolationMode +import imageio +import cv2 +import zipfile +import os +import glob +from .utils.mvbench import * + +FAIL_MSG = 'Failed to obtain answer via API.' + + +class MVBench(VideoBaseDataset): + + MD5 = 'fd21d36522cdedd46d84dc46715ad832' + SYS = """Carefully watch the video and pay attention to the cause and sequence of events, \ +the detail and movement of objects, and the action and pose of persons. \ +Based on your observations, select the best option that accurately addresses the question. +""" + + TYPE = 'Video-MCQ' + + def __init__(self, dataset='MVBench', nframe=0, fps=-1): + self.type_data_list = { + 'Action Sequence': ('action_sequence.json', + 'your_data_path/star/Charades_v1_480/', 'video', True), # has start & end + 'Action Prediction': ('action_prediction.json', + 'your_data_path/star/Charades_v1_480/', 'video', True), # has start & end + 'Action Antonym': ('action_antonym.json', + 'your_data_path/ssv2_video/', 'video', False), + 'Fine-grained Action': ('fine_grained_action.json', + 'your_data_path/Moments_in_Time_Raw/videos/', 'video', False), + 'Unexpected Action': ('unexpected_action.json', + 'your_data_path/FunQA_test/test/', 'video', False), + 'Object Existence': ('object_existence.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Object Interaction': ('object_interaction.json', + 'your_data_path/star/Charades_v1_480/', 'video', True), # has start & end + 'Object Shuffle': ('object_shuffle.json', + 'your_data_path/perception/videos/', 'video', False), + 'Moving Direction': ('moving_direction.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Action Localization': ('action_localization.json', + 'your_data_path/sta/sta_video/', 'video', True), # has start & end + 'Scene Transition': ('scene_transition.json', + 'your_data_path/scene_qa/video/', 'video', False), + 'Action Count': ('action_count.json', + 'your_data_path/perception/videos/', 'video', False), + 'Moving Count': ('moving_count.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Moving Attribute': ('moving_attribute.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'State Change': ('state_change.json', + 'your_data_path/perception/videos/', 'video', False), + 'Fine-grained Pose': ('fine_grained_pose.json', + 'your_data_path/nturgbd/', 'video', False), + 'Character Order': ('character_order.json', + 'your_data_path/perception/videos/', 'video', False), + 'Egocentric Navigation': ('egocentric_navigation.json', + 'your_data_path/vlnqa/', 'video', False), + 'Episodic Reasoning': ('episodic_reasoning.json', + 'your_data_path/tvqa/frames_fps3_hq/', 'frame', True), # has start & end, read frame + 'Counterfactual Inference': ('counterfactual_inference.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + } + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['MVBench'] + + def prepare_dataset(self, dataset_name='MVBench', repo_id='OpenGVLab/MVBench'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not os.path.exists(data_file): + return False + + if md5(data_file) != self.MD5: + return False + + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'])): + return False + return True + + if modelscope_flag_set(): + repo_id = 'modelscope/MVBench' + + cache_path = get_cache_path(repo_id, branch='main') + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def unzip_hf_zip(pth): + pth = os.path.join(pth, 'video/') + for filename in os.listdir(pth): + if filename.endswith('.zip'): + # 构建完整的文件路径 + zip_path = os.path.join(pth, filename) + + # 解压 ZIP 文件 + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(pth) + + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if os.path.exists(data_file) and md5(data_file) == self.MD5: + return + json_data_dir = os.path.join(pth, 'json') + self.data_list = [] + for k, v in self.type_data_list.items(): + with open(os.path.join(json_data_dir, v[0]), 'r') as f: + json_data = json.load(f) + for data in json_data: + if os.path.exists(os.path.join(pth, v[1].replace('your_data_path', 'video'), data['video'])): + self.data_list.append({ + 'task_type': k, + 'prefix': v[1].replace('your_data_path', 'video'), + 'data_type': v[2], + 'bound': v[3], + 'start': data['start'] if 'start' in data.keys() else None, + 'end': data['end'] if 'end' in data.keys() else None, + 'video': data['video'], + 'question': data['question'], + 'answer': data['answer'], + 'candidates': data['candidates'] + }) + else: + print( + 'NTURGB-D zip file is removed according to MVBench, you can view it at ' + 'https://huggingface.co/datasets/OpenGVLab/MVBench for detailed reason.' + ) + raise Exception( + f"{os.path.join(v[1].replace('your_data_path', 'video'), data['video'])} does not exist" + ) + + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + def move_files(pth): + src_folder = os.path.join(pth, 'video/data0613') + if not os.path.exists(src_folder): + return + for subdir in os.listdir(src_folder): + subdir_path = os.path.join(src_folder, subdir) + if os.path.isdir(subdir_path): + for subsubdir in os.listdir(subdir_path): + subsubdir_path = os.path.join(subdir_path, subsubdir) + if os.path.isdir(subsubdir_path): + for item in os.listdir(subsubdir_path): + item_path = os.path.join(subsubdir_path, item) + target_folder = os.path.join(pth, 'video', subdir, subsubdir) + if not os.path.exists(target_folder): + os.makedirs(target_folder) + target_path = os.path.join(target_folder, item) + try: + shutil.move(item_path, target_path) + except Exception as e: + print(f"Error moving {item_path} to {target_path}: {e}") + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id, revision='master') + else: + hf_token = os.environ.get('HUGGINGFACE_TOKEN') + huggingface_hub.login(hf_token) + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + unzip_hf_zip(dataset_path) + move_files(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + self.decord_method = { + 'video': self.read_video, + 'gif': self.read_gif, + 'frame': self.read_frame, + } + + self.nframe = 8 + self.frame_fps = 3 + + # transform + self.transform = T.Compose([ + Stack(), + ToTorchFormatTensor() + ]) + + return dict(root=dataset_path, data_file=data_file) + + def get_index(self, bound, fps, max_frame, first_idx=0): + if bound: + start, end = bound[0], bound[1] + else: + start, end = -100000, 100000 + start_idx = max(first_idx, round(start * fps)) + end_idx = min(round(end * fps), max_frame) + seg_size = float(end_idx - start_idx) / self.num_segments + frame_indices = np.array([ + int(start_idx + (seg_size / 2) + np.round(seg_size * idx)) + for idx in range(self.num_segments) + ]) + return frame_indices + + def read_video(self, video_path, bound=None): + from decord import VideoReader, cpu + vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) + max_frame = len(vr) - 1 + fps = float(vr.get_avg_fps()) + + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=0) + for frame_index in frame_indices: + img = Image.fromarray(vr[frame_index].asnumpy()) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def read_gif(self, video_path, bound=None, fps=25): + gif = imageio.get_reader(video_path) + max_frame = len(gif) - 1 + + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=0) + for index, frame in enumerate(gif): + if index in frame_indices: + img = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB) + img = Image.fromarray(img) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def read_frame(self, video_path, bound=None, fps=3): + max_frame = len(os.listdir(video_path)) + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=1) # frame_idx starts from 1 + for frame_index in frame_indices: + img = Image.open(os.path.join(video_path, f'{frame_index:05d}.jpg')) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def save_video_frames(self, imgs, video_name, frames): + + frame_paths = self.frame_paths(video_name) + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + # 建议锁文件以 video_name 命名 + lock_path = osp.join(self.frame_root, f'{video_name}.lock') + with portalocker.Lock(lock_path, 'w', timeout=30): + # 锁内再判断一次,防止重复写 + if not np.all([osp.exists(p) for p in frame_paths]): + block_size = imgs.size(0) // frames + split_tensors = torch.split(imgs, block_size) + to_pil = transforms.ToPILImage() + images = [to_pil(arr) for arr in split_tensors] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def qa_template(self, data): + question = f"Question: {data['question']}\n" + question += 'Options:\n' + answer = data['answer'] + answer_idx = -1 + for idx, c in enumerate(eval(data['candidates'])): + question += f"({chr(ord('A') + idx)}) {c}\n" + if c == answer: + answer_idx = idx + question = question.rstrip() + answer = f"({chr(ord('A') + answer_idx)}) {answer}" + return question, answer + + def load_into_video_and_process(self, line): + try: + from moviepy.editor import VideoFileClip, ImageSequenceClip + except: + raise ImportError( + 'MoviePy is not installed, please install it by running "pip install moviepy==1.0.3"' + ) + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + + if line['data_type'] in ['gif'] or os.path.splitext(video_path)[1] in ['.webm']: + processed_video_path = video_path.replace(os.path.splitext(video_path)[1], '.mp4') + if not os.path.exists(processed_video_path): + # using MoviePy to transform GIF, webm into mp4 format + gif_clip = VideoFileClip(video_path) + gif_clip.write_videofile(processed_video_path, codec='libx264') + gif_clip.close() + elif line['data_type'] in ['frame']: + input_images = os.path.join(video_path, '*.jpg') + processed_video_path = f'{video_path}.mp4' + if not os.path.exists(processed_video_path): + # using MoviePy to transform images into mp4 + image_files = sorted(glob.glob(input_images)) + image_clip = ImageSequenceClip(image_files, fps=self.frame_fps) + image_clip.write_videofile(processed_video_path, codec='libx264') + image_clip.close() + else: + processed_video_path = video_path + + if line['bound']: + base_name, suffix = os.path.splitext(processed_video_path) + output_video_path = f'{base_name}_processed{suffix}' + if not os.path.exists(output_video_path): + video_clip = VideoFileClip(processed_video_path) + clip = video_clip.subclip(line['start'], min(line['end'], video_clip.duration)) + clip.write_videofile(output_video_path) + clip.close() + else: + output_video_path = processed_video_path + + return output_video_path + + def save_video_into_images(self, line): + bound = None + if line['bound']: + bound = ( + line['start'], + line['end'], + ) + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + decord_method = self.decord_method[line['data_type']] + self.num_segments = self.nframe + torch_imgs = decord_method(video_path, bound) + img_frame_paths = self.save_video_frames(torch_imgs, line['video'], self.num_segments) + return img_frame_paths + + def build_prompt(self, line, video_llm): + if self.fps > 0: + raise ValueError('MVBench does not support fps setting, please transfer to MVBench_MP4!') + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + question, answer = self.qa_template(line) + message = [dict(type='text', value=self.SYS, role='system')] + if video_llm: + new_video_path = self.load_into_video_and_process(line) + message.append(dict(type='video', value=new_video_path)) + else: + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=question)) + message.append(dict(type='text', value='\nOnly give the best option.')) + message.append(dict(type='text', value='Best option:(', role='assistant')) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, '_rating', 'json') + score_file = get_intermediate_file_path(eval_file, '_score') + + if not osp.exists(score_file): + model = judge_kwargs.setdefault('model', 'chatgpt-0125') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + data_un = data[~pd.isna(data['prediction'])] + + for idx in data_un['index']: + ans = data.loc[data['index'] == idx, 'answer'].values[0] + pred = data.loc[data['index'] == idx, 'prediction'].values[0] + options = eval(data.loc[data['index'] == idx, 'candidates'].values[0]) + answer_idx = -1 + for id, c in enumerate(options): + if c == ans: + answer_idx = id + ans = f"({chr(ord('A') + answer_idx)}) {ans}" + input_item = data.loc[data['index'] == idx].to_dict(orient='records')[0] + for id, option_content in enumerate(eval(input_item['candidates'])): + input_item[chr(ord('A') + id)] = option_content + if option_content == input_item['answer']: + input_item['answer'] = chr(ord('A') + id) + + if FAIL_MSG in pred: + data.loc[idx, 'score'] = -1 + else: + data.loc[idx, 'score'] = int(check_ans_with_model( + pred, ans, model, + input_item, + 'MVBench' + )) + + rejected = [x for x in data['score'] if x == -1] + + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating + + +class MVBench_MP4(VideoBaseDataset): + + MP4_MD5 = '5c8c6f8b7972c2de65a629590f7c42f5' + SYS = """Carefully watch the video and pay attention to the cause and sequence of events, \ +the detail and movement of objects, and the action and pose of persons. \ +Based on your observations, select the best option that accurately addresses the question. +""" + TYPE = 'Video-MCQ' + + def __init__(self, dataset='MVBench_MP4', nframe=0, fps=-1): + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['MVBench_MP4'] + + def prepare_dataset(self, dataset_name='MVBench_MP4', repo_id='OpenGVLab/MVBench'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not os.path.exists(data_file): + return False + + if md5(data_file) != self.MP4_MD5: + return False + + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'])): + return False + return True + + if modelscope_flag_set(): + repo_id = 'modelscope/MVBench' + + cache_path = get_cache_path(repo_id, branch='video') + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if os.path.exists(data_file) and md5(data_file) == self.MP4_MD5: + return + json_data_path = os.path.join(dataset_path, 'test.json') + json_data = load(json_data_path) + root_data_dict = json_data['root'] + self.data_list = [] + for k, v in json_data['meta'].items(): + for item in v: + self.data_list.append({ + 'task_type': k, + 'prefix': root_data_dict[k], + 'video': item['video'], + 'question': item['question'], + 'answer': item['answer'], + 'candidates': item['candidates'] + }) + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id, revision='video') + else: + hf_token = os.environ.get('HUGGINGFACE_TOKEN') + huggingface_hub.login(hf_token) + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset', revision='video') + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + # transform + self.transform = T.Compose([ + Stack(), + ToTorchFormatTensor() + ]) + + return dict(root=dataset_path, data_file=data_file) + + def qa_template(self, data): + question = f"Question: {data['question']}\n" + question += 'Options:\n' + answer = data['answer'] + answer_idx = -1 + for idx, c in enumerate(eval(data['candidates'])): + question += f"({chr(ord('A') + idx)}) {c}\n" + if c == answer: + answer_idx = idx + question = question.rstrip() + answer = f"({chr(ord('A') + answer_idx)}) {answer}" + return question, answer + + def get_index_by_frame(self, max_frame): + seg_size = float(max_frame) / self.num_segments + frame_indices = np.array([ + int((seg_size / 2) + np.round(seg_size * idx)) + for idx in range(self.num_segments) + ]) + return frame_indices + + def get_index_by_fps(self, vid, fps): + total_frames = len(vid) + video_fps = vid.get_avg_fps() + total_duration = total_frames / video_fps + required_frames = int(total_duration * fps) + step_size = video_fps / fps + frame_indices = np.array([int(i * step_size) for i in range(required_frames)]) + self.num_segments = len(frame_indices) + return frame_indices + + def read_video(self, video_path): + from decord import VideoReader, cpu + vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) + max_frame = len(vr) - 1 + + images_group = list() + if self.fps < 0: + frame_indices = self.get_index_by_frame(max_frame) + else: + frame_indices = self.get_index_by_fps(vr, self.fps) + + for frame_index in frame_indices: + img = Image.fromarray(vr[frame_index].asnumpy()) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def save_video_frames(self, imgs, video_name, frames): + if self.fps > 0: + frame_paths = self.frame_paths_fps(video_name, frames) + else: + frame_paths = self.frame_paths(video_name) + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.join(self.frame_root, f'{video_name}.lock') + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + block_size = imgs.size(0) // frames + split_tensors = torch.split(imgs, block_size) + to_pil = transforms.ToPILImage() + images = [to_pil(arr) for arr in split_tensors] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def save_video_into_images(self, line): + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + if self.fps <= 0: + self.num_segments = self.nframe + else: + self.num_segments = 0 + torch_imgs = self.read_video(video_path) + img_frame_paths = self.save_video_frames(torch_imgs, line['video'], self.num_segments) + return img_frame_paths + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + question, answer = self.qa_template(line) + message = [dict(type='text', value=self.SYS, role='system')] + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + if video_llm: + message.append(dict(type='video', value=video_path)) + else: + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=question)) + message.append(dict(type='text', value='\nOnly give the best option.')) + message.append(dict(type='text', value='Best option:(', role='assistant')) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, '_rating', 'json') + score_file = get_intermediate_file_path(eval_file, '_score') + + if not osp.exists(score_file): + model = judge_kwargs.setdefault('model', 'chatgpt-0125') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + data_un = data[~pd.isna(data['prediction'])] + + for idx in data_un['index']: + ans = data.loc[data['index'] == idx, 'answer'].values[0] + pred = data.loc[data['index'] == idx, 'prediction'].values[0] + options = eval(data.loc[data['index'] == idx, 'candidates'].values[0]) + answer_idx = -1 + for id, c in enumerate(options): + if c == ans: + answer_idx = id + ans = f"({chr(ord('A') + answer_idx)}) {ans}" + input_item = data.loc[data['index'] == idx].to_dict(orient='records')[0] + for id, option_content in enumerate(eval(input_item['candidates'])): + input_item[chr(ord('A') + id)] = option_content + if option_content == input_item['answer']: + input_item['answer'] = chr(ord('A') + id) + + if FAIL_MSG in pred: + data.loc[idx, 'score'] = -1 + else: + data.loc[idx, 'score'] = int(check_ans_with_model( + pred, ans, model, + input_item, + 'MVBench_MP4' + )) + + rejected = [x for x in data['score'] if x == -1] + + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/sfebench.py b/VLMEvalKit-sudoku/vlmeval/dataset/sfebench.py new file mode 100644 index 0000000000000000000000000000000000000000..b1100b9e6ad5b04c853e22bea2393764a58bfdbe --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/sfebench.py @@ -0,0 +1,223 @@ +import string +from vlmeval import * +from ..smp import * +from ..smp.file import get_intermediate_file_path +from .image_vqa import ImageVQADataset +from .utils.judge_util import build_judge +from ..utils import track_progress_rich + +EVAL_TEMPLATE = """ +You are a strict evaluator assessing answer correctness. You must score the model's prediction on a scale from 0 to 9. +0 represents an entirely incorrect answer and 9 indicates a highly correct answer. + +# Input +Question +{question} +Ground Truth Answer +{answer} +Model Prediction +{prediction} + +# Evaluation Rules +- The model prediction may contain the reasoning process, you should spot the final answer +from it. +- For multiple-choice questions: Assign a higher score if the predicted answer matches the +ground truth, either by option letters or content. Include partial credit for answers that are +close in content. +- For exact match and open-ended questions: + - Assign a high score if the prediction matches the answer semantically, considering variations in format. + - Deduct points for partially correct answers or those with incorrect additional information. +- Ignore minor differences in formatting, capitalization, or spacing since the model may explain in a different way. +- Treat numerical answers as correct if they match within reasonable precision +- For questions requiring units, both value and unit must be correct + +# Scoring Guide +Provide a single integer from 0 to 9 to reflect your judgment of the answer's correctness. +# Strict Output format example +4 +""" + + +def report_score(df): + # assert group in [None, 'category'] + res = defaultdict(list) + + if 'split' in df: + splits = list(set(df['split'])) + res['split'] = splits + else: + df['split'] = ['none'] * len(df) + res['split'] = ['none'] + + for group in [None, 'category']: + if group is None: + res['Overall'] = [np.mean(df[df['split'] == sp]['score']) / 9 * 100 for sp in res['split']] + elif group not in df: + continue + else: + abilities = list(set(df[group])) + abilities.sort() + for ab in abilities: + sub_df = df[df[group] == ab] + res[ab] = [np.mean(sub_df[sub_df['split'] == sp]['score']) / 9 * 100 for sp in res['split']] + return pd.DataFrame(res) + + +def make_prompt(line): + question = line['question'] + answer = line['answer'] + tmpl = EVAL_TEMPLATE + prompt = tmpl.format( + question=question, + answer=answer, + prediction=line['prediction'] + ) + return prompt + + +def SFE_auxeval(model, data): + if isinstance(data, pd.DataFrame) and len(data) > 1: + lt = len(data) + for i in range(lt): + total_score = 0 + item = data.iloc[i] + prompt = make_prompt(item) + retry = 3 + for j in range(retry): + output = model.generate(prompt, temperature=0.5 * j) + if output.isdigit() and 0 <= int(output) <= 9: + total_score += int(output) + break + avg_score = total_score / lt + return dict(score=avg_score, log='Success to Judge') + else: + item = data.iloc[0] if isinstance(data, pd.DataFrame) else data + prompt = make_prompt(item) + retry = 3 + for i in range(retry): + output = model.generate(prompt, temperature=0.5 * i) + if output.isdigit() and 0 <= int(output) <= 9: + return dict(score=int(output), log='Success to Judge') + return dict(score=0, log='Fail to Judge') + + +class SFE(ImageVQADataset): + + DATASET_URL = { + 'SFE': 'https://opencompass.openxlab.space/utils/VLMEval/SFE.tsv', + 'SFE-zh': 'https://opencompass.openxlab.space/utils/VLMEval/SFE-zh.tsv' + } + + DATASET_MD5 = { + 'SFE': 'd4601425e7c9a62446b63a1faee17da5', + 'SFE-zh': '3e0250b7f30da55bf8f7b95eace66d82' + } + + MCQ_PROMPT = ( + "You are an expert in {discipline} and need to solve the following question. " + + "The question is a multiple-choice question. " + + "Answer with the option letter from the given choices." + ) + + EXACT_MATCH_PROMPT = ( + "You are an expert in {discipline} and need to solve the following question. " + + "The question is an exact match question. Answer the question using a single word or phrase." + ) + + OPEN_QUESTION_PROMPT = ( + "You are an expert in {discipline} and need to solve the following question. " + + "The question is an open-ended question. Answer the question using a phrase." + ) + + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + tgt_path = self.dump_image(line) + + question_type = line['question_type'] + field = line['category'] + question = line['question'] + + if question_type == 'exact_match': + prompt = self.EXACT_MATCH_PROMPT.format(discipline=field) + question = prompt + " " + question + elif question_type == 'mcq': + prompt = self.MCQ_PROMPT.format(discipline=field) + question = prompt + " " + question + if not pd.isna(line['A']): + question += '\nChoices are:\n' + for ch in string.ascii_uppercase[:15]: + if not pd.isna(line[ch]): + question += f'{ch}. {line[ch]}\n' + else: + break + elif question_type == 'open_ended': + prompt = self.OPEN_QUESTION_PROMPT.format(discipline=field) + question = prompt + " " + question + + prompt_segs = question.split('') + assert len(prompt_segs) == len(tgt_path) + 1 + msgs = [] + for i in range(len(tgt_path)): + text = prompt_segs[i].strip() + if text != '': + msgs.append(dict(type='text', value=text)) + msgs.append(dict(type='image', value=tgt_path[i])) + text = prompt_segs[-1].strip() + if text != '': + msgs.append(dict(type='text', value=text)) + return msgs + + def evaluate(self, eval_file, **judge_kwargs): + data = load(eval_file) + _ = self.dataset_name + assert 'answer' in data and 'prediction' in data + data['prediction'] = [str(x) for x in data['prediction']] + data['answer'] = [str(x) for x in data['answer']] + storage = get_intermediate_file_path(eval_file, '_judge') + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + if not osp.exists(storage): + ans_map = {} if not osp.exists(tmp_file) else load(tmp_file) + + model = judge_kwargs.pop('model', 'gpt-4o-1120') + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(model=model, **judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + model = None + else: + model = None + warnings.warn('OPENAI_API_KEY is not working properly, will use exact matching for evaluation') + + if model is not None: + if 'g_index' not in data: + lines = [data.iloc[i] for i in range(len(data))] + indices = [x['index'] for x in lines if x['index'] not in ans_map] + lines = [x for x in lines if x['index'] not in ans_map] + tups = [(model, line) for line in lines] + else: + main_data = data[[x == y for x, y in zip(data['index'], data['g_index'])]] + lines = [data[data['g_index'] == x] for x in main_data['index']] + indices = [x.iloc[0]['g_index'] for x in lines if x.iloc[0]['g_index'] not in ans_map] + lines = [x for x in lines if x.iloc[0]['g_index'] not in ans_map] + tups = [(model, x) for x in lines] + data = main_data + + if len(lines): + res = track_progress_rich( + SFE_auxeval, tups, nproc=nproc, chunksize=nproc, keys=indices, save=tmp_file) + for k, v in zip(indices, res): + ans_map[k] = v + + judge_results = [ans_map[x] for x in data['index']] + data['score'] = [x['score'] for x in judge_results] + dump(data, storage) + data = load(storage) + score = report_score(data) + + score_file = get_intermediate_file_path(eval_file, '_score', 'csv') + dump(score, score_file) + return score diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/slidevqa.py b/VLMEvalKit-sudoku/vlmeval/dataset/slidevqa.py new file mode 100644 index 0000000000000000000000000000000000000000..c6aa68575fe5f5aa5c9d12fb7f8ef757d4f37a27 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/slidevqa.py @@ -0,0 +1,189 @@ +import re +import math +from typing import List + +from vlmeval.dataset.utils.judge_util import build_judge +from vlmeval.smp import * +from .image_base import ImageBaseDataset +from .mmlongbench import concat_images, MMLongBench_auxeval, anls_compute +from ..smp.file import get_intermediate_file_path + + +FAIL_MSG = 'Failed to obtain answer via API.' + + +def get_f1(gt, pred): + gt_bow, pred_bow = gt.strip().split(), pred.strip().split() + if not gt_bow or not pred_bow: + return 0.0 + + recall = len([pred_e for pred_e in pred_bow if pred_e in gt_bow]) / len(gt_bow) + precision = len([pred_e for pred_e in pred_bow if pred_e in gt_bow]) / len(pred_bow) + f1 = 2 * recall * precision / (recall + precision) if (recall + precision) > 1e-4 else 0.0 + return f1 + + +def SlideVQA_acc(result_file): + data = load(result_file) + anls_list, em_list, f1_list = list(), list(), list() + for i in range(len(data)): + item = data.iloc[i] + if isinstance(item['answer'], float) and math.isnan(item['answer']): + item['answer'] = 'Not answerable' + + item['answer'] = re.sub('\n', '', item['answer']).lower() + item['pred'] = str(item['pred']).lower() + anls_score = anls_compute(item['answer'], item['pred']) + em_score = (item['answer'].strip() == item['pred'].strip()) + f1_score = get_f1(item['answer'], item['pred']) + anls_list.append(anls_score) + em_list.append(em_score) + f1_list.append(f1_score) + print('---------------------') + print(item['answer'], item['pred'], anls_score, em_score, f1_score) + + data['anls'] = anls_list + data['em'] = em_list + data['f1'] = f1_list + dump(data, result_file) + + res = dict() + res['category'], res['num'] = ['anls', 'EM', 'F1'], [len(data), len(data), len(data)] + res['avg'] = [sum(anls_list) / len(data), sum(em_list) / len(data), sum(f1_list) / len(data)] + res = pd.DataFrame(res) + return res + + +class SlideVQA(ImageBaseDataset): + + TYPE = 'VQA' + + DATASET_URL = { + 'SLIDEVQA_MINI': 'https://opencompass.openxlab.space/utils/VLMEval/SLIDEVQA_MINI.tsv', + 'SLIDEVQA': 'https://opencompass.openxlab.space/utils/VLMEval/SLIDEVQA.tsv', + } + DATASET_MD5 = { + 'SLIDEVQA_MINI': '6d9a8d8814fa5b7669deb2af3a3208eb', + 'SLIDEVQA': '5e822c2f800e94c1e23badfd478326b6', + } + + SUPPORTED_MODELS = { + 'GPT4': (1, 1), + 'GPT4V': (1, 1), + 'GPT4V_HIGH': (1, 1), + 'GPT4o': (1, 1), + 'GPT4o_HIGH': (1, 1), + 'GPT4o_MINI': (1, 1), + 'XComposer2d5': (1, -1), + 'XComposer2_4KHD': (1, -1), + 'MiniCPM-Llama3-V-2_5': (1, 5), + 'InternVL-Chat-V1-5': (5, 2), + } + + def __init__(self, dataset, **kwargs): + self.model_list = list(self.SUPPORTED_MODELS.keys()) + model_name = kwargs['model'] + if not listinstr(self.model_list, model_name): + raise AssertionError("{} doesn't support the evaluation on SlideVQA.".format(model_name)) + super(SlideVQA, self).__init__(dataset) + + self.is_api = True if listinstr(['GPT4'], model_name) else False + self.max_pages = 120 + concat_num, column_num = self.SUPPORTED_MODELS.get(model_name) + self.concat_num = concat_num + self.column_num = column_num + + def dump_image(self, origin_line): + os.makedirs(self.img_root, exist_ok=True) + + line = origin_line.copy() + if not isinstance(line['image_path'], List): + line['image_path'] = [line['image_path']] + line['image_path'] = line['image_path'][:self.max_pages] + + if 'image' in line: + if isinstance(line['image'], list): + tgt_path = [] + assert 'image_path' in line + for img, im_name in zip(line['image'], line['image_path']): + path = osp.join(self.img_root, im_name) + if not read_ok(path): + decode_base64_to_image_file(img, path) + tgt_path.append(path) + else: + tgt_path = osp.join(self.img_root, f"{line['index']}.jpg") + if not read_ok(tgt_path): + decode_base64_to_image_file(line['image'], tgt_path) + tgt_path = [tgt_path] + else: + assert 'image_path' in line + tgt_path = toliststr(line['image_path']) + + if self.concat_num > 0 and not self.is_api: + concatenated_images = concat_images(tgt_path, max_concat=self.concat_num, column_num=self.column_num) + + old_tgt_path = tgt_path + assert isinstance(old_tgt_path, list) + if self.column_num != -1: + tgt_path = [ + '_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat{}_{}.jpg'.format(self.concat_num, i) + for i in range(len(concatenated_images)) + ] + else: + tgt_path = ['_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat_all.jpg'] + + for path, concatenated_image in zip(tgt_path, concatenated_images): + if not read_ok(path): + decode_base64_to_image_file(encode_image_to_base64(concatenated_image), path) + num_images, image_size = len(old_tgt_path), concatenated_image.size + print('concat {} images to a new one with size {}. save at {}'.format(num_images, image_size, path)) + return tgt_path + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + logger = get_logger('Evaluation') + model = judge_kwargs['model'] + + storage = get_intermediate_file_path(eval_file, f'_{model}') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + + if osp.exists(storage): + logger.warning(f'GPT scoring file {storage} already exists, will reuse it in SlideVQA_eval. ') + else: + data = load(eval_file) + model = build_judge(max_tokens=128, **judge_kwargs) + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + new_results = list() + for model, line in tqdm(tups): + res = MMLongBench_auxeval(model, line) + new_results.append(res) + + log_map, res_map, pred_map = {}, {}, {} + all_inds = [line['index'] for line in lines] + for k, v in zip(all_inds, new_results): + log_map[k] = v['log'] + res_map[k] = v['res'] + pred_map[k] = v['pred'] + data['res'] = [res_map[idx] for idx in data['index']] + data['log'] = [log_map[idx] for idx in data['index']] + data['pred'] = [pred_map[idx] for idx in data['index']] + dump(data, storage) + + score = SlideVQA_acc(storage) + score_pth = get_intermediate_file_path(storage, '_score', 'csv') + + dump(score, score_pth) + logger.info(f'SlideVQA successfully finished evaluating {eval_file}, results saved in {score_pth}') + logger.info('Score: ') + logger.info(score) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/tamperbench.py b/VLMEvalKit-sudoku/vlmeval/dataset/tamperbench.py new file mode 100644 index 0000000000000000000000000000000000000000..7aebb48138122f3637ca2b94ec144a470fa19be8 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/tamperbench.py @@ -0,0 +1,537 @@ +import huggingface_hub +from huggingface_hub import snapshot_download +from ..smp import * +from ..smp.file import get_intermediate_file_path, get_file_extension +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +import torchvision.transforms as T +from torchvision import transforms +import imageio +import cv2 +import zipfile +import os +import glob +from .utils.tamperbench import * +import warnings + +# constants +FAIL_MSG = 'Failed to obtain answer via API.' + + +class MVTamperBench(VideoBaseDataset): + + BASENAME = "MVTamperBench" + MD5 = { + 'MVTamperBench': '3557260881ba47db8add440c5edb742a', + 'MVTamperBenchStart': 'c1d3c299ddbff6000f0d9cad820187b8', + 'MVTamperBenchEnd': 'aa2c19dd02e1b006ee2d4be9f6f2b62b', + } + SYS = """Carefully watch the video and pay attention to the cause and sequence of events, \ +""" + + TYPE = 'Video-MCQ' + + def __init__(self, dataset='MVTamperBench', nframe=0, fps=-1): + self.dataset_name = dataset + self.type_data_list = { + 'Action Sequence': ('action_sequence.json', + 'your_data_path/star/Charades_v1_480/', 'video', False), # has start & end + 'Action Prediction': ('action_prediction.json', + 'your_data_path/star/Charades_v1_480/', 'video', False), # has start & end + 'Action Antonym': ('action_antonym.json', + 'your_data_path/ssv2_video/', 'video', False), + 'Fine-grained Action': ('fine_grained_action.json', + 'your_data_path/Moments_in_Time_Raw/videos/', 'video', False), + 'Unexpected Action': ('unexpected_action.json', + 'your_data_path/FunQA_test/test/', 'video', False), + 'Object Existence': ('object_existence.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Object Interaction': ('object_interaction.json', + 'your_data_path/star/Charades_v1_480/', 'video', False), # has start & end + 'Object Shuffle': ('object_shuffle.json', + 'your_data_path/perception/videos/', 'video', False), + 'Moving Direction': ('moving_direction.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Action Localization': ('action_localization.json', + 'your_data_path/sta/sta_video/', 'video', False), # has start & end + 'Scene Transition': ('scene_transition.json', + 'your_data_path/scene_qa/video/', 'video', False), + 'Action Count': ('action_count.json', + 'your_data_path/perception/videos/', 'video', False), + 'Moving Count': ('moving_count.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'Moving Attribute': ('moving_attribute.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + 'State Change': ('state_change.json', + 'your_data_path/perception/videos/', 'video', False), + 'Character Order': ('character_order.json', + 'your_data_path/perception/videos/', 'video', False), + 'Egocentric Navigation': ('egocentric_navigation.json', + 'your_data_path/vlnqa/', 'video', False), + 'Episodic Reasoning': ('episodic_reasoning.json', + 'your_data_path/tvqa/frames_fps3/', 'video', False), # has start & end + 'Counterfactual Inference': ('counterfactual_inference.json', + 'your_data_path/clevrer/video_validation/', 'video', False), + } + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['MVTamperBench', 'MVTamperBenchStart', 'MVTamperBenchEnd'] + + def prepare_dataset(self, dataset_name='MVTamperBench', repo_id=None): + if repo_id: + dataset_name = repo_id.split('/')[-1] + else: + repo_id = f'Srikant86/{dataset_name}' + + def check_integrity(pth): + """ + Verifies the completeness and consistency of the dataset located at the specified path. + + Args: + path_to_dataset (str): The directory path where the dataset is stored. + + Returns: + bool: True if the dataset is intact, False otherwise. + """ + # Construct the full path to the data file + data_file = osp.join(pth, f'{dataset_name}.tsv') + + # Check if the data file exists + if not os.path.exists(data_file): + # If the data file doesn't exist, immediately return False + return False + # Verify the integrity of the data file by checking its MD5 hash + if md5(data_file) != self.MD5[dataset_name]: + return False + # Load the data from the data file + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'])): + return False + # If all checks pass, the dataset is considered intact + return True + + cache_path = get_cache_path(repo_id, branch='main') + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def unzip_hf_zip(pth): + pth = os.path.join(pth, 'video/') + for filename in os.listdir(pth): + if filename.endswith('.zip'): + # 构建完整的文件路径 + zip_path = os.path.join(pth, filename) + + # 解压 ZIP 文件 + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extractall(pth) + + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if os.path.exists(data_file) and md5(data_file) == self.MD5[dataset_name]: + return + json_data_dir = os.path.join(dataset_path, 'json') + self.data_list = [] + for k, v in self.type_data_list.items(): + with open(os.path.join(json_data_dir, v[0]), 'r') as f: + json_data = json.load(f) + for data in json_data: + if os.path.exists( + os.path.join(dataset_path, v[1].replace('your_data_path', 'video'), data['video'])): + self.data_list.append({ + 'task_type': k, + 'prefix': v[1].replace('your_data_path', 'video'), + 'data_type': v[2], + 'bound': v[3], + 'start': data['start'] if 'start' in data.keys() else None, + 'end': data['end'] if 'end' in data.keys() else None, + 'video': data['video'], + 'question': data['question'], + 'answer': data['answer'], + 'candidates': data['candidates'], + 'tamper_type': data['tamper_type'], + 'task_tamper_type': f"{k}_{data['tamper_type']}" + }) + + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + def move_files(pth): + # special for mvbench/data0613 supplementary data + src_folder = os.path.join(pth, 'video/data0613') + if not os.path.exists(src_folder): + return + for subdir in os.listdir(src_folder): + subdir_path = os.path.join(src_folder, subdir) + if os.path.isdir(subdir_path): + for subsubdir in os.listdir(subdir_path): + subsubdir_path = os.path.join(subdir_path, subsubdir) + if os.path.isdir(subsubdir_path): + for item in os.listdir(subsubdir_path): + item_path = os.path.join(subsubdir_path, item) + target_folder = os.path.join(pth, 'video', subdir, subsubdir) + if not os.path.exists(os.path.join(target_folder, item)): + shutil.move(item_path, os.path.join(target_folder, item)) + + src_folder = os.path.join(pth, 'video/perception') + if not os.path.exists(src_folder): + return + for subdir in os.listdir(src_folder): + subdir_path = os.path.join(src_folder, subdir) + if os.path.isdir(subdir_path): + for subsubdir in os.listdir(subdir_path): + subsubdir_path = os.path.join(subdir_path, subsubdir) + if os.path.isdir(subsubdir_path): + if not os.path.exists(src_folder): + return + for item in os.listdir(subsubdir_path): + item_path = os.path.join(subsubdir_path, item) + target_folder = os.path.join(pth, 'video/perception', subdir) + if not os.path.exists(os.path.join(target_folder, item)): + shutil.move(item_path, target_folder) + + hf_token = os.environ.get('HUGGINGFACE_TOKEN') + huggingface_hub.login(hf_token) + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + unzip_hf_zip(dataset_path) + move_files(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + self.decord_method = { + 'video': self.read_video, + 'gif': self.read_gif, + 'frame': self.read_frame, + } + + self.nframe = 8 + self.frame_fps = 3 + + # transform + self.transform = T.Compose([ + Stack(), + ToTorchFormatTensor() + ]) + + return dict(root=dataset_path, data_file=data_file) + + def get_index(self, bound, fps, max_frame, first_idx=0): + start, end = bound if bound else (-100000, 100000) + start_idx = max(first_idx, round(start * fps)) + end_idx = min(round(end * fps), max_frame) + seg_size = (end_idx - start_idx) / self.num_segments + mid_seg_size = seg_size / 2 + indices = np.arange(self.num_segments) + frame_indices = start_idx + mid_seg_size + np.round(seg_size * indices) + return frame_indices.astype(int) + + def read_video(self, video_path, bound=None): + from decord import VideoReader, cpu + vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) + max_frame = len(vr) - 1 + fps = float(vr.get_avg_fps()) + + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=0) + for frame_index in frame_indices: + img = Image.fromarray(vr[frame_index].asnumpy()) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def read_gif(self, video_path, bound=None, fps=25): + gif = imageio.get_reader(video_path) + max_frame = len(gif) - 1 + + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=0) + for index, frame in enumerate(gif): + if index in frame_indices: + img = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB) + img = Image.fromarray(img) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def read_frame(self, video_path, bound=None, fps=3): + """ + Reads frames from a video directory, processes them, and returns a tensor of images. + + Args: + video_path (str): Path to the directory containing video frames. + bound (tuple, optional): A tuple specifying the range of frames to read. Defaults to None. + fps (int, optional): Frames per second to sample from the video. Defaults to 3. + + Returns: + torch.Tensor: A tensor containing the processed images. + """ + max_frame = len(os.listdir(video_path)) + images_group = list() + frame_indices = self.get_index(bound, fps, max_frame, first_idx=1) # frame_idx starts from 1 + for frame_index in frame_indices: + img = Image.open(os.path.join(video_path, f'{frame_index:05d}.jpg')) + images_group.append(img) + torch_imgs = self.transform(images_group) + return torch_imgs + + def save_video_frames(self, imgs, video_name, frames): + + frame_paths = self.frame_paths(video_name) + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.join(self.frame_root, f'{video_name}.lock') + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + block_size = imgs.size(0) // frames + split_tensors = torch.split(imgs, block_size) + to_pil = transforms.ToPILImage() + images = [to_pil(arr) for arr in split_tensors] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def qa_template(self, data): + question = f"Question: {data['question']}\n" + question += 'Options:\n' + answer = data['answer'] + answer_idx = -1 + for idx, c in enumerate(eval(data['candidates'])): + question += f"({chr(ord('A') + idx)}) {c}\n" + if c == answer: + answer_idx = idx + question = question.rstrip() + answer = f"({chr(ord('A') + answer_idx)}) {answer}" + return question, answer + + def load_into_video_and_process(self, line): + """ + Loads a video or image sequence, processes it, and returns the path to the processed video. + + Args: + line (dict): A dictionary containing the following keys: + - 'prefix' (str): The prefix path to the video or image sequence. + - 'video' (str): The video file name or directory containing image frames. + - 'data_type' (str): The type of data, either 'gif', 'webm', or 'frame'. + - 'bound' (bool): Whether to process a subclip of the video. + - 'start' (float): The start time of the subclip (if 'bound' is True). + - 'end' (float): The end time of the subclip (if 'bound' is True). + + Returns: + str: The path to the processed video file. + + Raises: + ImportError: If MoviePy is not installed. + """ + try: + from moviepy.editor import VideoFileClip, ImageSequenceClip + except: + raise ImportError( + 'MoviePy is not installed, please install it by running "pip install moviepy==1.0.3"' + ) + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + + if line['data_type'] in ['gif'] or os.path.splitext(video_path)[1] in ['.webm']: + processed_video_path = video_path.replace(os.path.splitext(video_path)[1], '.mp4') + if not os.path.exists(processed_video_path): + # using MoviePy to transform GIF, webm into mp4 format + gif_clip = VideoFileClip(video_path) + gif_clip.write_videofile(processed_video_path, codec='libx264') + gif_clip.close() + elif line['data_type'] in ['frame']: + input_images = os.path.join(video_path, '*.jpg') + processed_video_path = f'{video_path}.mp4' + if not os.path.exists(processed_video_path): + # using MoviePy to transform images into mp4 + image_files = sorted(glob.glob(input_images)) + image_clip = ImageSequenceClip(image_files, fps=self.frame_fps) + image_clip.write_videofile(processed_video_path, codec='libx264') + image_clip.close() + else: + processed_video_path = video_path + + if line['bound']: + base_name, suffix = os.path.splitext(processed_video_path) + output_video_path = f'{base_name}_processed{suffix}' + if not os.path.exists(output_video_path): + video_clip = VideoFileClip(processed_video_path) + clip = video_clip.subclip(line['start'], min(line['end'], video_clip.duration)) + clip.write_videofile(output_video_path) + clip.close() + else: + output_video_path = processed_video_path + + return output_video_path + + def save_video_into_images(self, line): + bound = None + if line['bound']: + bound = ( + line['start'], + line['end'], + ) + video_path = os.path.join(self.data_root, line['prefix'], line['video']) + decord_method = self.decord_method[line['data_type']] + self.num_segments = self.nframe + torch_imgs = decord_method(video_path, bound) + img_frame_paths = self.save_video_frames(torch_imgs, line['video'], self.num_segments) + return img_frame_paths + + def build_prompt(self, line, video_llm): + """ + Builds a prompt for a language model based on the provided data and settings. + + Args: + line (int or dict): Either an integer index into the dataset or dictionary representing a single data point. + video_llm (bool): Whether to use a video-based language model or process individual frames as images. + + Returns: + list: A list of dictionaries representing the constructed prompt, where each dictionary contains the type + and value of the prompt element. + + Raises: + ValueError: If the frame rate (fps) is greater than zero, indicating that this method + is not compatible with MVBench's requirements. + """ + # Ensure that the frame rate is not set, as MVBench does not support it + if self.fps > 0: + raise ValueError('MVBench does not support fps setting, please transfer to MVBench_MP4!') + + # If line is an integer, retrieve the corresponding data point from the d + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + # Generate the question and answer pair based on the current data point + question, answer = self.qa_template(line) + # Initialize the prompt with a system message + message = [dict(type='text', value=self.SYS, role='system')] + # Add the generated question to the prompt + message.append(dict(type='text', value=question)) + # Process the video data according to the specified mode + if video_llm: + # Load the video and process it for the video-based langua + new_video_path = self.load_into_video_and_process(line) + message.append(dict(type='video', value=new_video_path)) + else: + # Save the video as individual image frames for processing + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + # Add instructions to the prompt + message.append(dict(type='text', value='\nOnly give the best option.')) + # Indicate the start of the assistant's response + message.append(dict(type='text', value='Best option:(', role='assistant')) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + """ + Evaluates the given evaluation file and generates ratings based on different dimensions. + + Args: + eval_file (str): Path to the evaluation file. The file should be in a supported format (xlsx/json/tsv). + **judge_kwargs: Additional keyword arguments for the judge model. + + Returns: + dict: A dictionary containing ratings for task type, tamper type, and task-tamper type. + + Raises: + AssertionError: If the eval_file is not a supported format. + Warning: If the OPENAI API is not working properly or the API key is not set, + exact matching will be used for evaluation. + + Notes: + - The function generates temporary files and score files based on the eval_file name. + - If the score file already exists, it will be used directly. + - The function processes the data, evaluates predictions, and calculates scores. + - Ratings are generated for different dimensions and saved to respective files. + """ + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + tgt_task_type_file = get_intermediate_file_path(eval_file, '_task_type_rating', 'json') + tgt_tamper_type_file = get_intermediate_file_path(eval_file, '_tamper_type_rating', 'json') + tgt_task_tamper_type_file = get_intermediate_file_path(eval_file, '_task_tamper_type_rating', 'json') + score_file = get_intermediate_file_path(eval_file, '_score') + score_metrics_file = get_intermediate_file_path(eval_file, '_score_f1') + action_metrics_file = get_intermediate_file_path(eval_file, '_action_f1') + + if not osp.exists(score_file): + model = judge_kwargs.setdefault('model', 'chatgpt-0125') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + data_un = data[~pd.isna(data['prediction'])] + + for idx in data_un['index']: + ans = data.loc[data['index'] == idx, 'answer'].values[0] + pred = data.loc[data['index'] == idx, 'prediction'].values[0] + options = eval(data.loc[data['index'] == idx, 'candidates'].values[0]) + answer_idx = -1 + for id, c in enumerate(options): + if c == ans: + answer_idx = id + ans = f"({chr(ord('A') + answer_idx)}) {ans}" + input_item = data.loc[data['index'] == idx].to_dict(orient='records')[0] + for id, option_content in enumerate(eval(input_item['candidates'])): + input_item[chr(ord('A') + id)] = option_content + if option_content == input_item['answer']: + input_item['answer'] = chr(ord('A') + id) + + if FAIL_MSG in pred: + data.loc[idx, 'score'] = -1 + else: + data.loc[idx, 'score'] = int(check_ans_with_model( + pred, ans, model, + input_item, + 'MVTamperBench' + )) + + rejected = [x for x in data['score'] if x == -1] + + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + model_name = score_file.split(f"_{self.BASENAME}")[0].split("/")[-1] + + score_metrics = process_results(score_file, model_name) + dump(score_metrics, score_metrics_file) + + action_metrics = aggregate_metrics_with_macro_average(score_file) + dump(action_metrics, action_metrics_file) + + rating_task_type = get_dimension_rating(score_file, 'task_type') + dump(rating_task_type, tgt_task_type_file) + rating_tamper_type = get_dimension_rating(score_file, 'tamper_type') + dump(rating_tamper_type, tgt_tamper_type_file) + rating_task_tamper_type = get_dimension_rating(score_file, 'task_tamper_type') + dump(rating_task_tamper_type, tgt_task_tamper_type_file) + rating = {**rating_task_type, **rating_tamper_type, **rating_task_tamper_type} + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/tempcompass.py b/VLMEvalKit-sudoku/vlmeval/dataset/tempcompass.py new file mode 100644 index 0000000000000000000000000000000000000000..6c409334e0e7f8c25eaec879612c7027697d504b --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/tempcompass.py @@ -0,0 +1,646 @@ +import huggingface_hub +from huggingface_hub import snapshot_download +from ..smp import * +from .video_concat_dataset import ConcatVideoDataset +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..utils import track_progress_rich +import torchvision.transforms as T +from torchvision import transforms +from torchvision.transforms.functional import InterpolationMode +from .utils.tempcompass import * + + +FAIL_MSG = 'Failed to obtain answer via API.' + + +class TempCompass(ConcatVideoDataset): + def __init__(self, dataset='TempCompass', nframe=0, fps=-1): + self.DATASET_SETS[dataset] = ['TempCompass_MCQ', 'TempCompass_Captioning', 'TempCompass_YorN'] + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['TempCompass'] + + def evaluate(self, eval_file, **judge_kwargs): + result = super().evaluate(eval_file=eval_file, **judge_kwargs) + result = result.reset_index().rename(columns={'index': 'dim.task_type'}) + score_file = get_intermediate_file_path(eval_file, '_acc', 'csv') + avg_dict = {} + for idx, item in result.iterrows(): + dim, task_type = item['dim.task_type'].split('. ') + if dim not in avg_dict: + avg_dict[dim] = {'success': 0.0, 'overall': 0.0} + if task_type not in avg_dict: + avg_dict[task_type] = {'success': 0.0, 'overall': 0.0} + if 'overall' not in avg_dict: + avg_dict['overall'] = {'success': 0.0, 'overall': 0.0} + avg_dict[dim]['success'] += item['success'] + avg_dict[dim]['overall'] += item['overall'] + avg_dict[task_type]['success'] += item['success'] + avg_dict[task_type]['overall'] += item['overall'] + avg_dict['overall']['success'] += item['success'] + avg_dict['overall']['overall'] += item['overall'] + result.loc[idx, 'acc'] = round(item['success'] / item['overall'] * 100, 2) + for key, value in avg_dict.items(): + # 使用 loc 方法添加新行 + result.loc[len(result)] = { + 'dim.task_type': key, + 'success': value['success'], + 'overall': value['overall'], + 'acc': round(value['success'] / value['overall'] * 100, 2) + } + dump(result, score_file) + return result + + +class TempCompass_MCQ(VideoBaseDataset): + + MD5 = '7efbb9e6d9dabacd22daf274852691dd' + TYPE = 'Video-MCQ' + + def __init__(self, dataset='TempCompass_MCQ', nframe=0, fps=-1): + self.type_data_list = { + 'multi-choice': ('multi-choice.json', './videos', '.mp4'), + 'caption_matching': ('caption_matching.json', './videos', '.mp4'), + } + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['TempCompass_MCQ'] + + def prepare_dataset(self, dataset_name='TempCompass_MCQ', repo_id='lmms-lab/TempCompass'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not osp.exists(data_file): + return False + + if md5(data_file) != self.MD5: + return False + + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'] + item['suffix'])): + return False + return True + + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def read_parquet(pth): + import pandas as pd + for task_name in self.type_data_list.keys(): + if not osp.exists(osp.join(pth, f'{task_name}.json')): + data = pd.read_parquet(osp.join(pth, task_name, 'test-00000-of-00001.parquet')) + data.to_json(osp.join(pth, f'{task_name}.json'), orient='records', lines=False) + + def unzip_videos(pth): + import zipfile + if not osp.exists(osp.join(pth, 'videos')): + zip_file = osp.join(pth, 'tempcompass_videos.zip') + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + zip_ref.extractall(pth) + + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if osp.exists(data_file) and md5(data_file) == self.MD5: + return + self.data_list = [] + for k, v in self.type_data_list.items(): + with open(osp.join(pth, v[0]), 'r') as f: + json_data = json.load(f) + for data in json_data: + self.data_list.append({ + 'task_type': k, + 'prefix': v[1], + 'suffix': v[2], + 'video': data['video_id'], + 'question': data['question'].split('\n')[0], + 'answer': data['answer'], + 'dim': data['dim'], + 'candidates': data['question'].split('\n')[1:], + }) + + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id) + else: + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + read_parquet(dataset_path) + unzip_videos(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + return dict(root=dataset_path, data_file=data_file) + + def qa_template(self, data): + question = data['question'] + '\n' + '\n'.join(eval(data['candidates'])) + answer = data['answer'] + return question, answer + + def save_video_frames(self, line): + vid_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + import decord + vid = decord.VideoReader(vid_path) + video_info = { + 'fps': vid.get_avg_fps(), + 'n_frames': len(vid), + } + if self.nframe > 0 and self.fps < 0: + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + frame_paths = self.frame_paths(line['video']) + elif self.fps > 0: + # not constrained by num_frames, get frames by fps + total_duration = video_info['n_frames'] / video_info['fps'] + required_frames = int(total_duration * self.fps) + step_size = video_info['fps'] / self.fps + indices = [int(i * step_size) for i in range(required_frames)] + frame_paths = self.frame_paths_fps(line['video'], len(indices)) + + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.splitext(vid_path)[0] + '.lock' + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def save_video_into_images(self, line): + frame_paths = self.save_video_frames(line) + return frame_paths + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + question, answer = self.qa_template(line) + message = [] + video_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + if video_llm: + message.append(dict(type='video', value=video_path)) + else: + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=question)) + message.append(dict(type='text', value='\nPlease directly give the best option:')) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + model = judge_kwargs.get('model', 'exact_matching') + assert model in ['chatgpt-1106', 'exact_matching'] + judge_kwargs.update({ + "max_tokens": 128, + "temperature": 1.0, + "top_p": 1, + "presence_penalty": 1, + }) + + score_file = get_intermediate_file_path(eval_file, f'_{model}_score') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(score_file): + data = load(eval_file) + if model != 'exact_matching': + model = build_judge(system_prompt=sys_prompt, **judge_kwargs) + else: + model = None + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + _ = track_progress_rich( + evaluate_tempcompass_mcq, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file, + ) + ans = load(tmp_file) + for idx, item in data.iterrows(): + data.loc[idx, 'score'] = ans[idx]['rating'] + dump(data, score_file) + + rating = get_dimension_rating(score_file) + return rating + + +class TempCompass_Captioning(VideoBaseDataset): + + MD5 = '35be9bf2581ea7767f02e9a8f37ae1ab' + TYPE = 'Video-VQA' + + def __init__(self, dataset='TempCompass_Captioning', nframe=0, fps=-1): + self.type_data_list = { + 'captioning': ('captioning.json', './videos', '.mp4'), + } + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['TempCompass_Captioning'] + + def prepare_dataset(self, dataset_name='TempCompass_Captioning', repo_id='lmms-lab/TempCompass'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not osp.exists(data_file): + return False + + if md5(data_file) != self.MD5: + return False + + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'] + item['suffix'])): + return False + return True + + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def read_parquet(pth): + import pandas as pd + for task_name in self.type_data_list.keys(): + if not osp.exists(osp.join(pth, f'{task_name}.json')): + data = pd.read_parquet(osp.join(pth, task_name, 'test-00000-of-00001.parquet')) + data.to_json(osp.join(pth, f'{task_name}.json'), orient='records', lines=False) + + def unzip_videos(pth): + import zipfile + if not osp.exists(osp.join(pth, 'videos')): + zip_file = osp.join(pth, 'tempcompass_videos.zip') + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + zip_ref.extractall(pth) + + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if osp.exists(data_file) and md5(data_file) == self.MD5: + return + self.data_list = [] + for k, v in self.type_data_list.items(): + with open(osp.join(pth, v[0]), 'r') as f: + json_data = json.load(f) + for data in json_data: + self.data_list.append({ + 'task_type': k, + 'prefix': v[1], + 'suffix': v[2], + 'video': data['video_id'], + 'question': data['question'], + 'answer': data['answer'], + 'dim': data['dim'], + 'mc_question': data['mc_question'], + 'mc_answer': data['mc_answer'], + }) + + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id) + else: + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + read_parquet(dataset_path) + unzip_videos(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + return dict(root=dataset_path, data_file=data_file) + + def qa_template(self, data): + question = data['question'] + answer = data['answer'] + return question, answer + + def save_video_frames(self, line): + vid_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + import decord + vid = decord.VideoReader(vid_path) + video_info = { + 'fps': vid.get_avg_fps(), + 'n_frames': len(vid), + } + if self.nframe > 0 and self.fps < 0: + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + frame_paths = self.frame_paths(line['video']) + elif self.fps > 0: + # not constrained by num_frames, get frames by fps + total_duration = video_info['n_frames'] / video_info['fps'] + required_frames = int(total_duration * self.fps) + step_size = video_info['fps'] / self.fps + indices = [int(i * step_size) for i in range(required_frames)] + frame_paths = self.frame_paths_fps(line['video'], len(indices)) + + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.splitext(vid_path)[0] + '.lock' + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def save_video_into_images(self, line): + frame_paths = self.save_video_frames(line) + return frame_paths + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + question, answer = self.qa_template(line) + message = [] + video_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + if video_llm: + message.append(dict(type='video', value=video_path)) + else: + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=question)) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + model = judge_kwargs.setdefault('model', 'chatgpt-1106') + assert model in ['chatgpt-1106'] + judge_kwargs.update({ + "max_tokens": 128, + "temperature": 1.0, + "top_p": 1, + "presence_penalty": 1, + }) + + score_file = get_intermediate_file_path(eval_file, f'_{model}_score') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(score_file): + data = load(eval_file) + if model != 'exact_matching': + model = build_judge(system_prompt=sys_prompt, **judge_kwargs) + else: + model = None + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + _ = track_progress_rich( + evaluate_tempcompass_captioning, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file, + ) + ans = load(tmp_file) + for idx, item in data.iterrows(): + data.loc[idx, 'score'] = ans[idx]['rating'] + dump(data, score_file) + + rating = get_dimension_rating(score_file) + return rating + + +class TempCompass_YorN(VideoBaseDataset): + + MD5 = 'c72c046d7fa0e82c8cd7462f2e844ea8' + TYPE = 'Video-Y/N' + + def __init__(self, dataset='TempCompass_YorN', nframe=0, fps=-1): + self.type_data_list = { + 'yes_no': ('yes_no.json', './videos', '.mp4'), + } + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + + @classmethod + def supported_datasets(cls): + return ['TempCompass_YorN'] + + def prepare_dataset(self, dataset_name='TempCompass_YorN', repo_id='lmms-lab/TempCompass'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not osp.exists(data_file): + return False + + if md5(data_file) != self.MD5: + return False + + data = load(data_file) + for idx, item in data.iterrows(): + if not osp.exists(osp.join(pth, item['prefix'], item['video'] + item['suffix'])): + return False + return True + + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + def read_parquet(pth): + import pandas as pd + for task_name in self.type_data_list.keys(): + if not osp.exists(osp.join(pth, f'{task_name}.json')): + data = pd.read_parquet(osp.join(pth, task_name, 'test-00000-of-00001.parquet')) + data.to_json(osp.join(pth, f'{task_name}.json'), orient='records', lines=False) + + def unzip_videos(pth): + import zipfile + if not osp.exists(osp.join(pth, 'videos')): + zip_file = osp.join(pth, 'tempcompass_videos.zip') + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + zip_ref.extractall(pth) + + def generate_tsv(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if osp.exists(data_file) and md5(data_file) == self.MD5: + return + self.data_list = [] + for k, v in self.type_data_list.items(): + with open(osp.join(pth, v[0]), 'r') as f: + json_data = json.load(f) + for data in json_data: + self.data_list.append({ + 'task_type': k, + 'prefix': v[1], + 'suffix': v[2], + 'video': data['video_id'], + 'question': data['question'].split('\n')[0], + 'answer': data['answer'], + 'dim': data['dim'] + }) + + data_df = pd.DataFrame(self.data_list) + data_df = data_df.assign(index=range(len(data_df))) + data_df.to_csv(data_file, sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id) + else: + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + read_parquet(dataset_path) + unzip_videos(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + return dict(root=dataset_path, data_file=data_file) + + def qa_template(self, data): + question = data['question'] + answer = data['answer'] + return question, answer + + def save_video_frames(self, line): + vid_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + import decord + vid = decord.VideoReader(vid_path) + video_info = { + 'fps': vid.get_avg_fps(), + 'n_frames': len(vid), + } + if self.nframe > 0 and self.fps < 0: + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + frame_paths = self.frame_paths(line['video']) + elif self.fps > 0: + # not constrained by num_frames, get frames by fps + total_duration = video_info['n_frames'] / video_info['fps'] + required_frames = int(total_duration * self.fps) + step_size = video_info['fps'] / self.fps + indices = [int(i * step_size) for i in range(required_frames)] + frame_paths = self.frame_paths_fps(line['video'], len(indices)) + + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.splitext(vid_path)[0] + '.lock' + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + def save_video_into_images(self, line): + frame_paths = self.save_video_frames(line) + return frame_paths + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + question, answer = self.qa_template(line) + message = [] + video_path = osp.join(self.data_root, line['prefix'], line['video'] + line['suffix']) + if video_llm: + message.append(dict(type='video', value=video_path)) + else: + img_frame_paths = self.save_video_into_images(line) + for im in img_frame_paths: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=question)) + message.append(dict(type='text', value='\nPlease answer yes or no:')) + return message + + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + model = judge_kwargs.get('model', 'exact_matching') + assert model in ['chatgpt-1106', 'exact_matching'] + judge_kwargs.update({ + "max_tokens": 128, + "temperature": 1.0, + "top_p": 1, + "presence_penalty": 1, + }) + + score_file = get_intermediate_file_path(eval_file, f'_{model}_score') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(score_file): + data = load(eval_file) + if model != 'exact_matching': + model = build_judge(system_prompt=sys_prompt, **judge_kwargs) + else: + model = None + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = {} + if osp.exists(tmp_file): + ans = load(tmp_file) + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + _ = track_progress_rich( + evaluate_tempcompass_YorN, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file, + ) + ans = load(tmp_file) + for idx, item in data.iterrows(): + data.loc[idx, 'score'] = ans[idx]['rating'] + dump(data, score_file) + + rating = get_dimension_rating(score_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/text_mcq.py b/VLMEvalKit-sudoku/vlmeval/dataset/text_mcq.py new file mode 100644 index 0000000000000000000000000000000000000000..2879551a260ff441b68380487fc14c86896983c1 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/text_mcq.py @@ -0,0 +1,123 @@ +from .text_base import TextBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..smp import * +from ..smp.file import get_intermediate_file_path + + +class TextMCQDataset(TextBaseDataset): + TYPE = 'MCQ' + + DATASET_URL = {} + + DATASET_MD5 = {} + + def build_prompt(self, line): + + if isinstance(line, int): + line = self.data.iloc[line] + + question = line['question'] + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = 'Options:\n' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = '' + if hint is not None: + prompt += f'Hint: {hint}\n' + prompt += f'Question: {question}\n' + if len(options): + prompt += options_prompt + prompt += 'Please select the correct answer from the options above. \n' + + msgs = [] + + msgs.append(dict(type='text', value=prompt)) + + return msgs + + def evaluate(self, eval_file, **judge_kwargs): + from .utils.multiple_choice import report_acc, report_acc_MMT, mcq_circular_eval, mcq_vanilla_eval + # assert dataset is not None + dataset_map = { + 'MMBench_TEST_EN': 'MMBench', 'MMBench_TEST_EN_V11': 'MMBench_V11', + 'MMBench_TEST_CN': 'MMBench_CN', 'MMBench_TEST_CN_V11': 'MMBench_CN_V11' + } + dataset = self.dataset_name + if dataset in dataset_map: + dataset = dataset_map[dataset] + nproc = judge_kwargs.pop('nproc', 4) + + circular = False + model = judge_kwargs.get('model', 'exact_matching') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + name_str_map = {'chatgpt-0125': 'openai', 'gpt-4-0125': 'gpt4'} + name_str = name_str_map[model] if model in name_str_map else model + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + + result_file = get_intermediate_file_path(eval_file, f'_{name_str}_result', 'pkl') + + data = load(eval_file) + data = data.sort_values(by='index') + data['prediction'] = [str(x) for x in data['prediction']] + # If not choice label, then use lower case + for k in data.keys(): + data[k.lower() if k not in list(string.ascii_uppercase) else k] = data.pop(k) + + meta = self.data + meta_q_map = {x: y for x, y in zip(meta['index'], meta['question'])} + data_map = {x: y for x, y in zip(data['index'], data['question'])} + for k in data_map: + assert k in meta_q_map, ( + f'eval_file should be the same as or a subset of dataset {self.dataset_name}' + ) + + if circular: + data = mcq_circular_eval(model, data, meta, nproc, result_file, self.dataset_name) + else: + data = mcq_vanilla_eval(model, data, meta, nproc, result_file, self.dataset_name) + + # load split + eval_name_result = get_intermediate_file_path(eval_file, f'_{name_str}_result') + dump(data, eval_name_result) + data = load(eval_name_result) + + # May have different report acc functions for different datasets + if 'MMT' in dataset: + acc = report_acc_MMT(data) + else: + acc = report_acc(data) + + score_file = get_intermediate_file_path(eval_file, '_acc', 'csv') + dump(acc, score_file) + + return acc + + +class CustomTextMCQDataset(TextMCQDataset): + + def load_data(self, dataset): + data_path = osp.join(LMUDataRoot(), f'{dataset}.tsv') + + if file_size(data_path, 'GB') > 1: + local_path = data_path.replace('.tsv', '_local.tsv') + if not osp.exists(local_path) or os.environ.get('FORCE_LOCAL', None): + from ..tools import LOCALIZE + LOCALIZE(data_path, local_path) + data_path = local_path + return load(data_path) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/__init__.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d89f6f6b78a7da3c82d38d2060a015175f0274f2 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/__init__.py @@ -0,0 +1,12 @@ +from .kie_evaluator import KieEvaluator +from .doc_parsing_evaluator import ParsingEvaluator +from .ocr_evaluator import OcrEvaluator +from .common import summary + + +evaluator_map_info = { + "kie": KieEvaluator("kie"), + "doc_parsing": ParsingEvaluator("doc_parsing"), + "multi_lan_ocr": OcrEvaluator("multi_lan_ocr"), + "multi_scene_ocr": OcrEvaluator("multi_scene_ocr") +} diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/common.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/common.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce9bcb550c4d22e24f3d92654603d06c92662f6 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/common.py @@ -0,0 +1,222 @@ +import os +import json +import time +import sys +from abc import abstractmethod +from tabulate import tabulate + + +def pick_response_text(json_path): + """ + """ + try: + with open(json_path, "r") as f: + json_data = json.load(f) + except Exception as e: + print("--> file error: msg: {}, path: {}".format(e, json_path)) + return None + + for required_key in ["model_name", "response"]: + if required_key not in json_data: + print("--> required key not exists, name: {}, path: {}".format(required_key, json_path)) + return None + + model_name = json_data["model_name"] + model_response = json_data["response"] + + response_text = None + if model_name.startswith("gpt") or model_name.startswith("o1"): + response_text = model_response.get("data", {}).get("response", {}).get("choices", [{}])[0].get("message", {}).get("content", None) # noqa: E501 + elif model_name.startswith("local_"): + response_text = model_response + else: + if model_name.startswith("claude"): + content_list = model_response.get("content", None) + elif model_name.startswith("gemini"): + content_list = model_response.get("candidates", [{}])[0].get("content", {}).get("parts", None) + elif model_name.startswith("qwen"): + content_list = model_response.get("output", {}).get("choices", [{}])[0].get("message", {}).get("content", None) # noqa: E501 + else: + raise NotImplementedError("The pick_response_text NOT implemented for model: {}".format(model_name)) + + if isinstance(content_list, list) and len(content_list) > 0: + response_text = content_list[0].get("text", None) + + if response_text is None: + print("--> [error][{}] text pick error, path: {}".format(model_name, json_path)) + return response_text + + +def load_response_from_dir(res_dir): + """ + """ + response_info = {} + for file_name in os.listdir(res_dir): + file_path = os.path.abspath(os.path.join(res_dir, file_name)) + if not file_name.endswith(".json"): + print("--> skip: result file should be a json: but got: {}".format(file_path)) + continue + + response_text = pick_response_text(file_path) + if response_text is None: + continue + + file_name_wo_ext, ext = os.path.splitext(file_name) + response_info[file_name_wo_ext] = response_text + return response_info + + +class BaseMetric(object): + """ BaseMetric """ + """ OCRMetric """ + def __init__(self, group_name, **kwargs): + self.group_name = group_name + self.kwargs = kwargs + + def response_post_func(self, response_text, **kwargs): + return response_text + + @abstractmethod + # Given the prediction and gt, return the evaluation results in the format of a dictionary + # results should contain a 'summary' key, for example: + # { + # "summary": { + # "f1-score": 99.99, + # "metric_name": "metric_value" # used for summary,only metric info could be placed in this dict. + # }, + # "your other info": "xxx" + # } + def evaluate(self, response_info, gt_info, normalize_func=None, **kwargs): + pass + + def __call__(self, pdt_res_dir, gt_info, with_response_ratio=True, **kwargs): + if isinstance(pdt_res_dir, dict): + raw_response_info = pdt_res_dir + elif os.path.exists(pdt_res_dir) and os.path.isdir(pdt_res_dir): + raw_response_info = load_response_from_dir(pdt_res_dir) + else: + return ValueError("invalid input: response dict or folder are required, but got {}".format(pdt_res_dir)) + + post_error_list, response_info = [], {} + response_error_list = list(gt_info.keys() - raw_response_info.keys()) + for file_name, single_pdt_str in raw_response_info.items(): + single_pdt_str = self.response_post_func(single_pdt_str, **kwargs) + if single_pdt_str is None: + post_error_list.append(file_name) + continue + response_info[file_name] = single_pdt_str + + meta_info = { + "gt_total_num": len(gt_info), "pdt_total_num": len(response_info), + "post_error_list": post_error_list, "response_error_list": response_error_list, + } + eval_info = self.evaluate(response_info, gt_info, **kwargs) + + # add response_success_ratio + if "summary" in eval_info and with_response_ratio: + success_ratio = (len(response_info) + len(post_error_list)) / (len(gt_info) + 1e-9) + eval_info["summary"].update({"response_success_ratio": success_ratio}) + return meta_info, eval_info + + +def summary(index_path, exp_dir_base, is_weighted_sum=False): + """ + """ + with open(index_path, "r") as f: + data_list = json.load(f) + + all_data_info = {} + for data_info_item in data_list: + data_name = data_info_item["dataset"] + if not data_info_item.get("release", True): + continue + all_data_info[data_name] = data_info_item + dataset_list = list(all_data_info.keys()) + summary_path = summary_multi_exp(exp_dir_base, dataset_list, is_weighted_sum=is_weighted_sum) + return summary_path + + +def summary_multi_exp(exp_dir_base, dataset_list=None, is_weighted_sum=False): + """ + """ + if dataset_list is None: + all_dataset_name = [] + for exp_name in os.listdir(exp_dir_base): + dir_status_path = os.path.join(exp_dir_base, exp_name, "status.json") + if not os.path.exists(dir_status_path): + continue + with open(dir_status_path, "r") as f: + data_status_info = json.load(f) + all_dataset_name.extend(data_status_info.keys()) + dataset_list = sorted(set(all_dataset_name)) + + # summary main code + all_evaluate_info, _ = {}, 0 + for exp_name in os.listdir(exp_dir_base): + dir_status_path = os.path.join(exp_dir_base, exp_name, "status.json") + if not os.path.exists(dir_status_path): + print("--> skip: status.json not exist: {}".format(dir_status_path)) + continue + + with open(dir_status_path, "r") as f: + all_status_info = json.load(f) + + for data_name in dataset_list: + total_num = all_status_info.get(data_name, {}).get("config", {}).get("num", "-1") + summary_info = all_status_info.get(data_name, {}).get("evaluation", {}).get("summary", {}) + for metric_name, metric_value in summary_info.items(): + if metric_name not in all_evaluate_info: + all_evaluate_info[metric_name] = {} + if exp_name not in all_evaluate_info[metric_name]: + all_evaluate_info[metric_name][exp_name] = {} + all_evaluate_info[metric_name][exp_name][data_name] = (metric_value, total_num) + + all_table_md = [] + for metric_name, metric_info in all_evaluate_info.items(): + formatted_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time())) + summary_line_list = [] + summary_key_name = "summary(weighted)" if is_weighted_sum else "summary" + summary_head = [f"exp_name({metric_name}_{formatted_time})"] + dataset_list + [summary_key_name] + for exp_name, data_eval_info in metric_info.items(): + summary_line = [exp_name, ] + + all_metric_value = 0 + is_summary_valid, all_total_num, all_weighted_metric = True, 0, 0 + for data_name in dataset_list: + metric_value, total_num = data_eval_info.get(data_name, ("-1", "-1")) + summary_line.append("{:.2f}".format(float(metric_value) * 100)) + if str(metric_value) == "-1" or str(metric_value) == "-1": + is_summary_valid = False + continue + + all_total_num += float(total_num) + all_weighted_metric += float(total_num) * float(metric_value) + all_metric_value += float(metric_value) + + summary_value_valid = ((all_weighted_metric / (all_total_num + 1e-9)) * 100) if is_weighted_sum \ + else (all_metric_value / (len(dataset_list) + 1e-9) * 100) + summary_value = "-" if not is_summary_valid else "{:.2f}".format(summary_value_valid) + summary_line.append(summary_value) + summary_line_list.append(summary_line) + + md_table_info = tabulate(summary_line_list, headers=summary_head, tablefmt='pipe') + all_table_md.append(md_table_info) + + print("\n\n".join(all_table_md)) + summary_path = os.path.abspath(os.path.join(exp_dir_base, "summary.md")) + with open(summary_path, "w") as f: + f.write("\n\n".join(all_table_md)) + return summary_path + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print("Usage: python {} exp_base_dir".format(__file__)) + exit(-1) + else: + print('--> info: {}'.format(sys.argv)) + exp_base_dir = sys.argv[1] + + summary_path = summary_multi_exp(exp_base_dir, dataset_list=None, is_weighted_sum=False) + print("--> info: summary saved at : {}".format(summary_path)) + print("happy coding.") diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/kie_evaluator.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/kie_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..797d4244608d44252d24e6b6aea742ba8c768da6 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/ccocr_evaluator/kie_evaluator.py @@ -0,0 +1,385 @@ + +""" +Donut +Copyright (c) 2022-present NAVER Corp. +MIT License +""" +import json +import os +import sys +import re +import time +from typing import Any, Dict, List, Tuple, Union + +import zss +from zss import Node +from collections import Counter +from nltk import edit_distance + +# local import +from .common import BaseMetric + + +def flatten(data: dict): + """ + Convert Dictionary into Non-nested Dictionary + Example: + input(dict) + { + "menu": [ + {"name" : ["cake"], "count" : ["2"]}, + {"name" : ["juice"], "count" : ["1"]}, + ] + } + output(list) + [ + ("menu.name", "cake"), + ("menu.count", "2"), + ("menu.name", "juice"), + ("menu.count", "1"), + ] + """ + flatten_data = list() + + def _flatten(value, key=""): + if type(value) is dict: + for child_key, child_value in value.items(): + _flatten(child_value, f"{key}.{child_key}" if key else child_key) + elif type(value) is list: + for value_item in value: + _flatten(value_item, key) + else: + flatten_data.append((key, value)) + + _flatten(data) + return flatten_data + + +def update_cost(node1: Node, node2: Node): + """ + Update cost for tree edit distance. + If both are leaf node, calculate string edit distance between two labels (special token '' will be ignored). + If one of them is leaf node, cost is length of string in leaf node + 1. + If neither are leaf node, cost is 0 if label1 is same with label2 othewise 1 + """ + label1 = node1.label + label2 = node2.label + label1_leaf = "" in label1 + label2_leaf = "" in label2 + if label1_leaf and label2_leaf: + return edit_distance(label1.replace("", ""), label2.replace("", "")) + elif not label1_leaf and label2_leaf: + return 1 + len(label2.replace("", "")) + elif label1_leaf and not label2_leaf: + return 1 + len(label1.replace("", "")) + else: + return int(label1 != label2) + + +def insert_and_remove_cost(node: Node): + """ + Insert and remove cost for tree edit distance. + If leaf node, cost is length of label name. + Otherwise, 1 + """ + label = node.label + if "" in label: + return len(label.replace("", "")) + else: + return 1 + + +def normalize_dict(data: Union[Dict, List, Any]): + """ + Sort by value, while iterate over element if data is list + """ + # if not data: + # return {} + + if isinstance(data, dict): + new_data = dict() + for key in sorted(data.keys(), key=lambda k: (len(k), k)): + value = normalize_dict(data[key]) + if value: + if not isinstance(value, list): + value = [value] + new_data[key] = value + + elif isinstance(data, list): + if all(isinstance(item, dict) for item in data): + new_data = [] + for item in data: + item = normalize_dict(item) + if item: + new_data.append(item) + else: + new_data = [str(item).strip() for item in data if type(item) in {str, int, float} and str(item).strip()] + else: + new_data = [str(data).strip()] + return new_data + + +def cal_f1_all(preds, answers): + """ + Calculate global F1 accuracy score (field-level, micro-averaged) by counting all true positives, + false negatives and false positives + """ + metric_info, error_info = {}, {} + total_tp, total_fn_or_fp = 0, 0 + for file_name, answer in answers.items(): + sample_error_info = {"fp": [], "fn": [], "tp": []} + pred = preds.get(file_name, {}) + pred, answer = flatten(normalize_dict(pred)), flatten(normalize_dict(answer)) + for field in pred: + field_name = field[0] + if field_name not in metric_info: + metric_info[field_name] = {"total_tp": 0, "total_fn_or_fp": 0} + if field in answer: + total_tp += 1 + metric_info[field_name]["total_tp"] += 1 + sample_error_info["tp"].append(field) + answer.remove(field) + else: + total_fn_or_fp += 1 + metric_info[field_name]["total_fn_or_fp"] += 1 + sample_error_info["fp"].append(field) + + total_fn_or_fp += len(answer) + for field in answer: + field_name = field[0] + if field_name not in metric_info: + metric_info[field_name] = {"total_tp": 0, "total_fn_or_fp": 0} + metric_info[field_name]["total_fn_or_fp"] += 1 + sample_error_info["fn"].append(field) + + sample_error_num = sum([len(v) for k, v in sample_error_info.items() if k != "tp"]) + if sample_error_num > 0: + sample_error_info["error_num"] = sample_error_num + error_class_list = ["counter_" + x[0] for x in (sample_error_info["fn"] + sample_error_info["fp"])] + counter = Counter(error_class_list) + sample_error_info["error_info"] = dict(counter) + error_info[file_name] = sample_error_info + + # summary + for field_name, field_info in metric_info.items(): + field_tp, field_fn_or_fp = field_info["total_tp"], field_info["total_fn_or_fp"] + metric_info[field_name]["acc"] = field_tp / (field_tp + field_fn_or_fp / 2 + 1e-6) + + print("donut_evaluator: total_tp: {}, total_fn_or_fp: {}, ptd_num: {}, gt_num: {}".format(total_tp, total_fn_or_fp, + len(preds), len(answers))) + error_info = {k: v for k, v in + sorted(error_info.items(), key=lambda item: item[1].get("error_num", 0), reverse=True)} + metric_info = {k: v for k, v in + sorted(metric_info.items(), key=lambda item: item[1].get("total_fn_or_fp", 0), reverse=True)} + return total_tp / (total_tp + total_fn_or_fp / 2 + 1e-6), metric_info, error_info + + +def construct_tree_from_dict(data: Union[Dict, List], node_name: str = None): + """ + Convert Dictionary into Tree + + Example: + input(dict) + + { + "menu": [ + {"name" : ["cake"], "count" : ["2"]}, + {"name" : ["juice"], "count" : ["1"]}, + ] + } + + output(tree) + + | + menu + / \ + + / | | \ + name count name count + / | | \ + cake 2 juice 1 + """ + if node_name is None: + node_name = "" + + node = Node(node_name) + + if isinstance(data, dict): + for key, value in data.items(): + kid_node = construct_tree_from_dict(value, key) + node.addkid(kid_node) + elif isinstance(data, list): + if all(isinstance(item, dict) for item in data): + for item in data: + kid_node = construct_tree_from_dict( + item, + "", + ) + node.addkid(kid_node) + else: + for item in data: + node.addkid(Node(f"{item}")) + else: + raise Exception(data, node_name) + return node + + +def cal_acc(pred: dict, answer: dict): + """ + Calculate normalized tree edit distance(nTED) based accuracy. + 1) Construct tree from dict, + 2) Get tree distance with insert/remove/update cost, + 3) Divide distance with GT tree size (i.e., nTED), + 4) Calculate nTED based accuracy. (= max(1 - nTED, 0 ). + """ + pred = construct_tree_from_dict(normalize_dict(pred)) + answer = construct_tree_from_dict(normalize_dict(answer)) + val1 = zss.distance( + pred, + answer, + get_children=zss.Node.get_children, + insert_cost=insert_and_remove_cost, + remove_cost=insert_and_remove_cost, + update_cost=update_cost, + return_operations=False, + ) + val2 = zss.distance( + construct_tree_from_dict(normalize_dict({})), + answer, + get_children=zss.Node.get_children, + insert_cost=insert_and_remove_cost, + remove_cost=insert_and_remove_cost, + update_cost=update_cost, + return_operations=False, + ) + return max(0, 1 - val1 / val2) + + +def cal_acc_all(pred_info, answer_info): + acc_info, error_info = {}, {} + for file_name, answer in answer_info.items(): + # if file_name not in pred_info: + # print("---> error: pdt not found: {}".format(file_name)) + # continue + pred = pred_info.get(file_name, {}) + acc = cal_acc(pred, answer) + acc_info[file_name] = acc + if acc < 1.0: + error_info[file_name] = {"acc": acc, "pred": pred, "answer": answer} + + error_info = {k: v for k, v in sorted(error_info.items(), key=lambda item: item[1].get("acc", 0))} + acc_averge = sum(list(acc_info.values())) / (len(acc_info) + 1e-6) + return acc_averge, error_info + + +def normalize_values_of_nested_dict(d, normalize_func): + """ + """ + if isinstance(d, dict): + return {k: normalize_values_of_nested_dict(v, normalize_func) for k, v in d.items()} + elif isinstance(d, list): + return [normalize_values_of_nested_dict(x, normalize_func) if isinstance(x, dict) else x for x in d] + elif isinstance(d, str): + return normalize_func(d) + else: + return d + + +def eval_donut(pdt_info, gt_info, normalize_func=None, data_name=None): + """ + """ + if normalize_func is not None: + print("--> info: normalize_func executed.") + pdt_info = normalize_values_of_nested_dict(pdt_info, normalize_func) + gt_info = normalize_values_of_nested_dict(gt_info, normalize_func) + + f1_score, class_eval_info, error_info = cal_f1_all(pdt_info, gt_info) + acc_average, acc_error_info = cal_acc_all(pdt_info, gt_info) + eval_info = {"f1_score": f1_score, "acc": acc_average, "class_f1_score": class_eval_info, + "f1_error_info": error_info, "acc_error_info": acc_error_info} + print(data_name, "f1_score", f1_score, "acc", acc_average) + return eval_info + + +def post_process_to_json(qwen_info_str, file_name=None): + try: + if "```json" in qwen_info_str: + if "```" not in qwen_info_str: + qwen_info_str += "```" + qwen_info_group = re.search(r'```json(.*?)```', qwen_info_str, re.DOTALL) + json_str = qwen_info_group.group(1).strip().replace("\n", "") + else: + json_str = qwen_info_str.strip().replace("\n", "") + json_data = json.loads(json_str) + return json_data + except Exception as err: # noqa: F841 + return None + + +def fullwidth_to_halfwidth(text): + # 全角转半角 + result = '' + for char in text: + code_point = ord(char) + # 全角空格直接转化 + if code_point == 0x3000: + code_point = 0x0020 + # 其他全角字符(除空格)转换为半角 + elif 0xFF01 <= code_point <= 0xFF5E: + code_point -= 0xFEE0 + result += chr(code_point) + result = result.replace("、", ",") + return result + + +def remove_unnecessary_spaces(text): + # 去掉中文字符之间的空格 + text = re.sub(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])', '', text) + # 去掉中文和英文、数字之间的空格 + text = re.sub(r'(?<=[\u4e00-\u9fff])\s+(?=[a-zA-Z0-9])', '', text) + text = re.sub(r'(?<=[a-zA-Z0-9])\s+(?=[\u4e00-\u9fff])', '', text) + # 去掉符号前的不必要空格,保留符号后的一个空格 + text = re.sub(r'(? bool: + if not isinstance(asw, str) != str or not isinstance(gt_asw, str): + print('Warning: input is not string') + print(asw, gt_asw) + asw = str(asw).lower().strip() + gt_asw = str(gt_asw).lower().strip() + if gt_asw == asw: + return True + try: + a = eval(gt_asw) + b = eval(asw) + if abs(a - b) < 1e-6: + return True + except: + pass + try: + a = latex2sympy(gt_asw) + b = latex2sympy(asw) + if abs(eval(str(a)) - eval(str(b))) < 1e-6: + return True + if abs(a - b) < 1e-6: + return True + except: + pass + return False + + +def get_gpt4_ICE(): + example_1 = """ +Hint: Please answer the question and provide the final answer at the end.\n +Question: Which number is missing?\n +Model response: The number missing in the sequence is 14.\n +Extracted answer: 14 +""" + + example_2 = """ +Hint: Please answer the question and provide the final answer at the end.\n +Question: What is the fraction of females facing the camera?\n +Model response: The fraction of females facing the camera is 0.6, +which means that six out of ten females in the group are facing the camera.\n +Extracted answer: 0.6 +""" + + example_3 = """ +Hint: Please answer the question and provide the final answer at the end.\n +Question: How much money does Luca need to buy a sour apple candy and a butter-scotch candy? (Unit: $)\n +Model response: Luca needs $1.45 to buy a sour apple candy and a butterscotch candy.\n +Extracted answer: 1.45 +""" + + example_4 = """ +Hint: Please answer the question and provide the final answer at the end.\n +Question: Between which two years does the line graph saw its maximum peak?\n +Model response: The line graph saw its maximum peak between 2007 and 2008.\n +Extracted answer: [2007, 2008] +""" + + example_5 = """ +Hint: Please answer the question and provide the correct option letter, e.g., A, B, C, D, at the end.\n +Question: What fraction of the shape is blue?\n +Choices: (A) 3/11 (B) 8/11 (C) 6/11 (D) 3/5\n +Model response: The correct answer is (B) 8/11.\n +Extracted answer: B +""" + + return [example_1, example_2, example_3, example_4, example_5] + + +def build_mathv_gpt4_prompt(line): + task_description = """ +Please read the following example. +Then extract the answer from the model response and type it at the end of the prompt.\n +""" + question = line['question'] + prediction = str(line['prediction']) + prompt = task_description + examples = get_gpt4_ICE() + for example in examples: + prompt += example + '\n' + prompt += question + '\n' + prompt += 'Model respone: ' + prediction + prompt += 'Extracted answer:' + return prompt + + +def list_to_dict(lst): + return {chr(65 + i): val for i, val in enumerate(lst)} + + +def post_check(line, prefetch=False): + res = None + ans = line['answer'] + response = line['prediction'] if prefetch else line['res'] + try: + if len(eval(line['choices'])) > 0: + ans = line['answer'] + choices = list_to_dict(eval(line['choices'])) + res = can_infer(response, choices) + if prefetch: + return res + else: + res = str(response) + ans = str(ans) + except ValueError: + pass + + try: + if is_equal(res, ans): + return res if prefetch else True + else: + return False + except Exception as err: + logging.warning(f'{type(err)}: {err}') + return False + + +def MATH_V_auxeval(model, line): + prompt = build_mathv_gpt4_prompt(line) + log = '' + retry = 5 + if post_check(line, prefetch=True): + res = post_check(line, prefetch=True) + return dict(log='Prefetch succeed', res=res) + for i in range(retry): + prediction = line['prediction'] + res = model.generate(prompt, temperature=i * 0.5) + + if FAIL_MSG in res: + log += f'Try {i}: output is {prediction}, failed to parse.\n' + else: + log += 'Succeed' + return dict(log=log, res=res) + log += 'All 5 retries failed.\n' + return dict(log=log, res='') + + +def MATH_V_acc(result_file): + data = load(result_file) + tot = defaultdict(lambda: 0) + fetch = defaultdict(lambda: 0) + hit = defaultdict(lambda: 0) + lt = len(data) + from tqdm import tqdm + for i in tqdm(range(lt)): + item = data.iloc[i] + cate = item['category'] + tot['Overall'] += 1 + tot[cate] += 1 + if item['log'] == 'Prefetch succeed': + fetch['Overall'] += 1 + fetch[cate] += 1 + if post_check(item, prefetch=False): + hit['Overall'] += 1 + hit[cate] += 1 + + res = defaultdict(list) + for k in tot.keys(): + res['Subject'].append(k) + res['tot'].append(tot[k]) + res['prefetch'].append(fetch[k]) + res['hit'].append(hit[k]) + res['prefetch_rate'].append(fetch[k] / tot[k] * 100) + res['acc'].append(hit[k] / tot[k] * 100) + res = pd.DataFrame(res).sort_values('Subject', ignore_index=True) + return res diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/mlvu.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/mlvu.py new file mode 100644 index 0000000000000000000000000000000000000000..c82fe3ee985d0560b4e34462ceb42d5690f57b5f --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/mlvu.py @@ -0,0 +1,189 @@ +from ...smp import * +from .multiple_choice import extract_answer_from_item +from PIL import Image, ImageOps +import numpy as np + +FAIL_MSG = 'Failed to obtain answer via API.' + +system_prompt_sub_scene = """ +##TASK DESCRIPTION: +You are required to evaluate a respondent's answer based on a provided question, some scoring points, and the respondent's answer. You should provide two scores. The first is the accuracy score, which should range from 1 to 5. The second is the relevance score, which should also range from 1 to 5. Below are the criteria for each scoring category. +##ACCURACY Scoring Criteria: +Evaluate the respondent's answer against specific scoring points as follows: +Score 1: The response completely misses the scoring point. +Score 3: The response mentions content related to the scoring point but is not entirely correct. +Score 5: The response accurately addresses the scoring point. +Calculate the average score across all scoring points to determine the final accuracy score. +##RELEVANCE Scoring Criteria: +Assess how the respondent's answer relates to the original question: +Score 1: The response is completely off-topic from the question. +Score 2: The response is partially related to the question but contains a significant amount of irrelevant content. +Score 3: The response primarily addresses the question, but the respondent seems uncertain about their own answer. +Score 4: The response mostly addresses the question and the respondent appears confident in their answer. +Score 5: The response is fully focused on addressing the question with no irrelevant content and demonstrates complete certainty. +---- +##INSTRUCTION: +1. Evaluate Accuracy: First, assess and score each scoring point based on the respondent's answer. Calculate the average of these scores to establish the final accuracy score. Provide a detailed rationale before assigning your score. +2. Evaluate RELEVANCE: Assess the relevance of the respondent’s answer to the question. Note that when evaluating relevance, the correctness of the answer is not considered; focus solely on how relevant the answer is to the question. Provide a comprehensive rationale before assigning your score. +3. Output Scores in JSON Format: Present the scores in JSON format as follows: +{'score_accuracy': score_acc, 'score_relevance': score_rele, 'total_score': score_acc + score_rele} +""" # noqa + +system_prompt_summary = """ +##TASK DESCRIPTION: +You are required to evaluate the performance of the respondent in the video summarization task based on the standard answer and the respondent's answer. You should provide two scores. The first is the COMPLETENESS score, which should range from 1 to 5. The second is the RELIABILITY score, which should also range from 1 to 5. Below are the criteria for each scoring category: +##COMPLETENESS Scoring Criteria: +The completeness score focuses on whether the summary covers all key points and main information from the video. +Score 1: The summary hardly covers any of the main content or key points of the video. +Score 2: The summary covers some of the main content and key points but misses many. +Score 3: The summary covers most of the main content and key points. +Score 4: The summary is very comprehensive, covering most to nearly all of the main content and key points. +Score 5: The summary completely covers all the main content and key points of the video. +##RELIABILITY Scoring Criteria: +The reliability score evaluates the correctness and clarity of the video summary. It checks for factual errors, misleading statements, and contradictions with the video content. If the respondent's answer includes details that are not present in the standard answer, as long as these details do not conflict with the correct answer and are reasonable, points should not be deducted. +Score 1: Contains multiple factual errors and contradictions; presentation is confusing. +Score 2: Includes several errors and some contradictions; needs clearer presentation. +Score 3: Generally accurate with minor errors; minimal contradictions; reasonably clear presentation. +Score 4: Very accurate with negligible inaccuracies; no contradictions; clear and fluent presentation. +Score 5: Completely accurate with no errors or contradictions; presentation is clear and easy to understand. +---- +##INSTRUCTION: +1. Evaluate COMPLETENESS: First, analyze the respondent's answer according to the scoring criteria, then provide an integer score between 1 and 5 based on sufficient evidence. +2. Evaluate RELIABILITY: First, analyze the respondent's answer according to the scoring criteria, then provide an integer score between 1 and 5 based on sufficient evidence. +3. Output Scores in JSON Format: Present the scores in JSON format as follows: +{'score_completeness': score_comp, 'score_reliability': score_reli, 'total_score': score_comp + score_reli} +""" # noqa + + +def check_ans_with_model(pred, gt, model, item, dataset_name='MLVU_MCQ'): + flag = False + + index = gt.index("(") # noqa + index2 = gt.index(")") # noqa + gt_option = gt[index + 1: index2] + + if ")" in pred: + index3 = pred.index(")") + pred = pred[index3 - 1: index3] + if pred == gt_option: + flag = True + elif extract_answer_from_item(model, item, dataset_name)['opt'] == item['answer']: + flag = True + + return flag + + +def extract_scores_summary(text): + # Define the keys to locate in the text + keys = ["score_completeness", "score_reliability"] + scores = [] + + for key in keys: + # Find the index where each key starts + start_index = text.find(key) + if start_index == -1: + continue # Skip if key is not found + + # Find the start of the number which is after the colon and space + start_number_index = text.find(":", start_index) + 2 + end_number_index = text.find(",", start_number_index) # Assuming the number ends before a comma + + # Extract and convert the number to float + score = float(text[start_number_index:end_number_index]) + scores.append(score) + + return scores + + +def check_ans_with_model_summary(pred, gt, model, item, dataset_name='MLVU_OpenEnded'): + user_prompt = f""" + Please score the respondent's answer according to the steps in the Instructions. You must end with a JSON dict to store the scores. + Standard Answer: {gt} + Respondent's Answer: {pred} + """ # noqa + result = model.generate(user_prompt) + result = extract_scores_summary(result) + result = np.sum(result) + return result + + +def extract_scores_sub_scene(text): + # Define the keys to locate in the text + keys = ["score_accuracy", "score_relevance"] + scores = [] + + for key in keys: + # Find the index where each key starts + start_index = text.find(key) + if start_index == -1: + continue # Skip if key is not found + + # Find the start of the number which is after the colon and space + start_number_index = text.find(":", start_index) + 2 + end_number_index = text.find(",", start_number_index) # Assuming the number ends before a comma + + # Extract and convert the number to float + score = float(text[start_number_index:end_number_index]) + scores.append(score) + + return scores + + +def check_ans_with_model_sub_scene(pred, gt, model, item, dataset_name='MLVU_OpenEnded'): + user_prompt = f""" + Please score the respondent's answer according to the steps in the Instructions. You must end with a JSON dict to store the scores. + Question: {item['question']} + Scoring Points: {item['scoring_points']} + Respondent's Answer: {pred} + """ # noqa + result = model.generate(user_prompt) + result = extract_scores_sub_scene(result) + result = np.sum(result) + return result + + +def MLVU_OpenEnded_generate(model, line): + task_type = line['task_type'] + if task_type == 'summary': + user_prompt = ( + f"Please score the respondent's answer according to the steps in the Instructions. " + f"You must end with a JSON dict to store the scores.\n" + f"Standard Answer: {line['answer']}\n" + f"Respondent's Answer: {line['prediction']}\n" + ) + elif task_type == 'sub_scene': + user_prompt = ( + f"Please score the respondent's answer according to the steps in the Instructions. " + f"You must end with a JSON dict to store the scores.\n" + f"Question: {line['question']}\n" + f"Scoring Points: {line['scoring_points']}\n" + f"Respondent's Answer: {line['prediction']}\n" + ) + else: + AssertionError(f'MLVU don\'t have {task_type} open ended task!') + result = model.generate(user_prompt) + return result + + +def MLVU_OpenEnded_extract(gpt_generate_data, org_data): + extract_func = { + 'sub_scene': extract_scores_sub_scene, + 'summary': extract_scores_summary + } + for idx, item in org_data.iterrows(): + func = extract_func[item['task_type']] + text = gpt_generate_data[idx] + org_data.loc[idx, 'score'] = np.sum(func(text)) + + return org_data + + +def get_dimension_rating(data_path): + data = load(data_path) + result_dict = {} + for idx, item in data.iterrows(): + if item['task_type'] not in result_dict: + result_dict[item['task_type']] = [0,0] + result_dict[item['task_type']][0] += int(item['score']) + result_dict[item['task_type']][1] += 1 + return result_dict diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/mmbench_video.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/mmbench_video.py new file mode 100644 index 0000000000000000000000000000000000000000..75514b09bfd3b459b872059f6f0a7373b0b9c21f --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/mmbench_video.py @@ -0,0 +1,70 @@ +from ...smp import * +import numpy as np + +FAIL_MSG = 'Failed to obtain answer via API.' + +system_prompt = """ +As an AI assistant, your task is to evaluate a candidate answer in comparison to a given correct answer. +The question itself, the correct 'groundtruth' answer, and the candidate answer will be provided to you. +Your assessment should range from 0 to 3, \ +based solely on the semantic similarity between the groundtruth and the candidate answer, \ +disregarding any grammatical differences. +A rating of 0 suggests no similarity, implying the candidate answer is entirely incorrect. +A rating of 1 suggests low similarity, meaning the candidate answer is largely incorrect. +A rating of 2 suggests high similarity, meaning the candidate answer is largely correct. +Lastly, a rating of 3 indicates complete similarity, which means the candidate answer is entirely correct. +Your response should be a single integer from 0, 1, 2, or 3. +""" + +MMV_DIMENSIONS = { + 'CP': ['Video Topic', 'Video Emotion', 'Video Scene', 'Video Style'], + 'FP-S': ['OCR', 'Object Recognition', 'Attribute Recognition', 'Event Recognition', 'Human Motion', 'Counting'], + 'FP-C': ['Spatial Relationship', 'Human-object Interaction', 'Human Interaction'], + 'HL': ['Hallucination'], + 'LR': ['Structuralized Image-Text Understanding', 'Mathematical Calculation'], + 'AR': ['Physical Property', 'Function Reasoning', 'Identity Reasoning'], + 'RR': ['Natural Relation', 'Physical Relation', 'Social Relation'], + 'CSR': ['Common Sense Reasoning'], + 'TR': ['Counterfactual Reasoning', 'Causal Reasoning', 'Future Prediction'], +} +L3_DIMS = [] +for k, v in MMV_DIMENSIONS.items(): + L3_DIMS.extend(v) + +MMV_DIMENSIONS['Perception'] = [] +MMV_DIMENSIONS['Reasoning'] = [] +MMV_DIMENSIONS['Overall'] = [] +for k in ['CP', 'FP-C', 'FP-S', 'HL']: + MMV_DIMENSIONS['Perception'].extend(MMV_DIMENSIONS[k]) + MMV_DIMENSIONS['Overall'].extend(MMV_DIMENSIONS[k]) +for k in ['LR', 'AR', 'RR', 'CSR', 'TR']: + MMV_DIMENSIONS['Reasoning'].extend(MMV_DIMENSIONS[k]) + MMV_DIMENSIONS['Overall'].extend(MMV_DIMENSIONS[k]) + + +def get_dimension_rating(data_path): + data = load(data_path) + coarse_rating = {k: [] for k in MMV_DIMENSIONS} + fine_rating = {k: [] for k in L3_DIMS} + + for i in range(len(data)): + cate = data.iloc[i]['dimensions'] + cates = eval(cate) + + for c in cates: + fine_rating[c].append(data.iloc[i]['score']) + + for d in MMV_DIMENSIONS: + if np.any([x in MMV_DIMENSIONS[d] for x in cates]): + coarse_rating[d].append(data.iloc[i]['score']) + + coarse_all = {k: f'{np.mean([max(x, 0) for x in v]):.2f}' for k, v in coarse_rating.items()} + coarse_valid = {k: f'{np.mean([x for x in v if x >= 0]):.2f}' for k, v in coarse_rating.items()} + fine_all = {k: f'{np.mean([max(x, 0) for x in v]):.2f}' for k, v in fine_rating.items()} + fine_valid = {k: f'{np.mean([x for x in v if x >= 0]):.2f}' for k, v in fine_rating.items()} + return dict(coarse_all=coarse_all, coarse_valid=coarse_valid, fine_all=fine_all, fine_valid=fine_valid) + + +def build_prompt(item): + tmpl = 'Question: {}\nGroundtruth answer: {}\nCandidate answer: {}\nYour response: ' + return tmpl.format(item['question'], item['answer'], item['prediction']) diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/spatial457.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/spatial457.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8581cd0ee9b0def52c04498b229609db6d8805 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/spatial457.py @@ -0,0 +1,169 @@ +SUPERCLRVER_sub_shape = { + "car": ["suv", "wagon", "minivan", "sedan", "truck", "addi", "car"], + "bus": ["articulated", "regular", "double", "school", "bus"], + "motorbike": ["chopper", "dirtbike", "scooter", "cruiser", "motorbike"], + "aeroplane": ["jet", "fighter", "biplane", "airliner", "aeroplane"], + "bicycle": ["road", "utility", "mountain", "tandem", "bicycle"], +} + +inverse_shape = {} +for key, value in SUPERCLRVER_sub_shape.items(): + for v in value: + inverse_shape[v] = key + + +class Spatial457_utils: + def __init__(self): + + return + + def get_random_answer(self, gt): + import random + + all_attributes = { + "size": ["small", "large"], + "shape": [ + "airliner", + "dirtbike", + "road bike", + "tandem bike", + "suv", + "wagon", + "scooter", + "mountain bike", + "minivan", + "sedan", + "school bus", + "fighter", + "chopper", + "double bus", + "truck", + "articulated bus", + "cruiser", + "jet", + "utility bike", + "regular bus", + "biplane", + ], + "color": [ + "gray", + "blue", + "purple", + "brown", + "green", + "cyan", + "red", + "yellow", + ], + "direction": ["left", "right", "front", "back"], + } + + gt = gt.lower() + if gt in ["yes", "no"]: + return random.choice(["yes", "no"]) + if gt in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: + return str(random.randint(0, 9)) + for key, value in all_attributes.items(): + if gt in value: + return random.choice(value) + + def all_answers(self): + all_attributes = { + "size": ["small", "large"], + "shape": [ + "airliner", + "dirtbike", + "road bike", + "tandem bike", + "suv", + "wagon", + "scooter", + "mountain bike", + "minivan", + "sedan", + "school bus", + "fighter", + "chopper", + "double bus", + "truck", + "articulated bus", + "cruiser", + "jet", + "utility bike", + "regular bus", + "biplane", + ], + "color": [ + "gray", + "blue", + "purple", + "brown", + "green", + "cyan", + "red", + "yellow", + ], + "direction": ["left", "right", "front", "back"], + } + + all_answers = "" + for key, value in all_attributes.items(): + captical_value = [x.capitalize() for x in value] + all_answers += ", ".join(captical_value) + ", " + return all_answers.strip(", ") + + def is_correct(self, answer, predict): + text2num = { + "zero": "0", + "one": "1", + "two": "2", + "three": "3", + "four": "4", + "five": "5", + "six": "6", + "seven": "7", + "eight": "8", + "nine": "9", + "ten": "10", + } + predict = str(predict) + answer = str(answer) + + if predict.lower() == "none": + predict = "no" + + if predict.lower() == answer.lower(): + return True + if predict == "0" and answer == "No": + return True + if predict.lower() in text2num and text2num[predict.lower()] == answer: + return True + if answer.lower() == "yes" and predict in [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + ]: + return True + + if self.category_correct(predict, answer): + return True + return False + + def category_correct(self, answer, gt_answer): + answer = str(answer).lower().split(" ")[0] + gt_answer = str(gt_answer).lower().split(" ")[0] + + if ( + answer in inverse_shape + and gt_answer in inverse_shape + and inverse_shape[answer] == inverse_shape[gt_answer] + ): + return True + + return False diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/treebench.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/treebench.py new file mode 100644 index 0000000000000000000000000000000000000000..afb2e3b90bb48afa33900a46dc4982debce57de3 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/treebench.py @@ -0,0 +1,65 @@ +from ...smp import * +import numpy as np +import re + + +def get_dimension_rating(data_path): + P_SUBTASKS = [ + 'Attributes', + 'Material', + 'Physical State', + 'Object Retrieval', + 'OCR', + ] + + R_SUBTASKS = [ + 'Perspective Transform', + 'Ordering', + 'Contact and Occlusion', + 'Spatial Containment', + 'Comparison', + ] + + data = load(data_path) + results = {} + results['Overall'] = {} + results['Perception'] = {} + for subtask in P_SUBTASKS: + results['Perception'][subtask] = {'true': 0, 'false': 0} + results['Reasoning'] = {} + for subtask in R_SUBTASKS: + results['Reasoning'][subtask] = {'true': 0, 'false': 0} + + all_iou = [] + + for i in range(len(data)): + question = data.iloc[i] + Task = question['category'].split('/')[0] + Subtask = question['category'].split('/')[1] + if question['score'] >= 0: + cnt = question['score'] + results[Task][Subtask]['true'] += cnt + results[Task][Subtask]['false'] += 1 - cnt + all_iou.append(question['iou']) + + sum_all, succ_all = 0, 0 + for task, tasks_values in results.items(): + cnt_task, sum_task = 0, 0 + for substask, subtask_value in tasks_values.items(): + cnt_subtask, sum_subtask = 0, 0 + cnt_subtask += subtask_value['true'] + sum_subtask += subtask_value['false'] + subtask_value['true'] + if (subtask_value['false'] + subtask_value['true']) > 0: + acc = subtask_value['true'] / (subtask_value['false'] + subtask_value['true']) + else: + acc = 0 + results[task][substask] = acc + + cnt_task += cnt_subtask + sum_task += sum_subtask + succ_all += cnt_task + sum_all += sum_task + # results[task]['Overall'] = acc_task + results['Overall'] = succ_all / sum_all + results['mIoU'] = np.mean(all_iou) + return results diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/vcrbench/cau_acc.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/vcrbench/cau_acc.py new file mode 100644 index 0000000000000000000000000000000000000000..5ffcd022385301616682664d389b066f1e28a261 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/vcrbench/cau_acc.py @@ -0,0 +1,113 @@ +import json +import os +from collections import defaultdict +import sys +import pandas as pd + + +def xlsx2json(xlsx_file, json_file): + df = pd.read_excel(xlsx_file) + df.to_json(json_file, orient='records') + + +def calculate_accuracy(data): + total_correct = 0 + total_items = len(data) + + dimension_stats = defaultdict(lambda: {"correct": 0, "total": 0}) + duration_stats = { + "0-60": {"correct": 0, "total": 0}, + "60-300": {"correct": 0, "total": 0}, + "300+": {"correct": 0, "total": 0} + } + + for item in data: + if item.get("answer_scoring") == '1': + total_correct += 1 + + dimension = item.get("dimension") + if dimension: + dimension_stats[dimension]["total"] += 1 + if item.get("answer_scoring") == '1': + dimension_stats[dimension]["correct"] += 1 + + duration = item.get("duration", 0) + if duration <= 60: + key = "0-60" + elif duration <= 300: + key = "60-300" + else: + key = "300+" + + duration_stats[key]["total"] += 1 + if item.get("answer_scoring") == '1': + duration_stats[key]["correct"] += 1 + + overall_accuracy = total_correct / total_items if total_items > 0 else 0 + + dimension_accuracy = {} + for dimension, stats in dimension_stats.items(): + dimension_accuracy[dimension] = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 + + duration_accuracy = {} + for key, stats in duration_stats.items(): + duration_accuracy[key] = stats["correct"] / stats["total"] if stats["total"] > 0 else 0 + + return { + "overall_accuracy": overall_accuracy, + "dimension_accuracy": dimension_accuracy, + "duration_accuracy": duration_accuracy + } + + +def format_results(results): + formatted_results = {} + + formatted_results["Overall Accuracy"] = f"{results['overall_accuracy']:.3f}" + + formatted_results["Accuracy by Dimension"] = { + dimension: f"{accuracy:.3f}" for dimension, accuracy in results["dimension_accuracy"].items() + } + + formatted_results["Accuracy by Duration"] = { + duration: f"{accuracy:.3f}" for duration, accuracy in results["duration_accuracy"].items() + } + + return formatted_results + + +def calu_acc_main(file_path, txt_file): + + # Load data from the provided file path + data = json.load(open(file_path, 'r', encoding='utf-8')) + for item in data: + item["answer_scoring"] = str(item["answer_scoring"]) + + results = calculate_accuracy(data) + formatted_results = format_results(results) + + print("===== Statistics =====") + print("Overall Accuracy:", formatted_results["Overall Accuracy"]) + print("\nAccuracy by Dimension:") + for dimension, accuracy in formatted_results["Accuracy by Dimension"].items(): + print(f" {dimension}: {accuracy}") + print("\nAccuracy by Duration:") + for duration, accuracy in formatted_results["Accuracy by Duration"].items(): + print(f" {duration}: {accuracy}") + + print('\n\n') + + with open(txt_file, 'w') as file: + file.write("===== Statistics =====\n") + file.write(f"Overall Accuracy: {formatted_results['Overall Accuracy']}\n") + file.write("\nAccuracy by Dimension:\n") + + for dimension, accuracy in formatted_results["Accuracy by Dimension"].items(): + file.write(f" {dimension}: {accuracy}\n") + + file.write("\nAccuracy by Duration:\n") + + for duration, accuracy in formatted_results["Accuracy by Duration"].items(): + file.write(f" {duration}: {accuracy}\n") + + file.write('\n\n') diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/utils/videomme.py b/VLMEvalKit-sudoku/vlmeval/dataset/utils/videomme.py new file mode 100644 index 0000000000000000000000000000000000000000..dea57ead7ed6cbb700b95eda15c6eec2fb45b77f --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/utils/videomme.py @@ -0,0 +1,150 @@ +from ...smp import * +from .multiple_choice import extract_answer_from_item +import numpy as np +import re + +FAIL_MSG = 'Failed to obtain answer via API.' + +DURATIONS = [ + 'short', + 'medium', + 'long', +] + +DOMAINS = [ + 'Knowledge', + 'Film & Television', + 'Sports Competition', + 'Artistic Performance', + 'Life Record', + 'Multilingual' +] + +SUB_CATEGORIES = [ + 'Humanity & History', + 'Literature & Art', + 'Biology & Medicine', + 'Finance & Commerce', + 'Astronomy', + 'Geography', + 'Law', + 'Life Tip', + 'Technology', + 'Animation', + 'Movie & TV Show', + 'Documentary', + 'News Report', + 'Esports', + 'Basketball', + 'Football', + 'Athletics', + 'Other Sports', + 'Stage Play', + 'Magic Show', + 'Variety Show', + 'Acrobatics', + 'Handicraft', + 'Food', + 'Fashion', + 'Daily Life', + 'Travel', + 'Pet & Animal', + 'Exercise', + 'Multilingual' +] + +TASK_CATEGORIES = [ + 'Temporal Perception', + 'Spatial Perception', + 'Attribute Perception', + 'Action Recognition', + 'Object Recognition', + 'OCR Problems', + 'Counting Problem', + 'Temporal Reasoning', + 'Spatial Reasoning', + 'Action Reasoning', + 'Object Reasoning', + 'Information Synopsis', +] + + +def get_dimension_rating(data_path): + data = load(data_path) + + duration_rating = {k: {} for k in DURATIONS} + for duration in DURATIONS + ['overall']: + duration_rating[duration] = { + 'overall': '', + 'domain': {k: [] for k in DOMAINS}, + 'sub_category': {k: [] for k in SUB_CATEGORIES}, + 'task_type': {k: [] for k in TASK_CATEGORIES} + } + + for i in range(len(data)): + + domain = data.iloc[i]['domain'] + sub_ctg = data.iloc[i]['sub_category'] + task_ctg = data.iloc[i]['task_type'] + + duration = data.iloc[i]['duration'] + duration_rating[duration]['domain'][domain].append(data.iloc[i]['score']) + duration_rating[duration]['sub_category'][sub_ctg].append(data.iloc[i]['score']) + duration_rating[duration]['task_type'][task_ctg].append(data.iloc[i]['score']) + + duration_rating['overall']['domain'][domain].append(data.iloc[i]['score']) + duration_rating['overall']['sub_category'][sub_ctg].append(data.iloc[i]['score']) + duration_rating['overall']['task_type'][task_ctg].append(data.iloc[i]['score']) + + for duration in DURATIONS + ['overall']: + + overall_res_dur = f'{np.mean([x for x in sum(duration_rating[duration]["domain"].values(), []) if x >= 0]):.3f}' + duration_rating[duration]['overall'] = overall_res_dur + + for domain in DOMAINS: + domain_res_dur = f'{np.mean([x for x in duration_rating[duration]["domain"][domain] if x >= 0]):.3f}' + duration_rating[duration]['domain'][domain] = domain_res_dur + + for sub_ctg in SUB_CATEGORIES: + sub_res_dur = f'{np.mean([x for x in duration_rating[duration]["sub_category"][sub_ctg] if x >= 0]):.3f}' + duration_rating[duration]['sub_category'][sub_ctg] = sub_res_dur + + for task_ctg in TASK_CATEGORIES: + task_res_dur = f'{np.mean([x for x in duration_rating[duration]["task_type"][task_ctg] if x >= 0]):.3f}' + duration_rating[duration]['task_type'][task_ctg] = task_res_dur + + return duration_rating + + +def extract_option(model, input_item, dataset_name): + options = input_item['question'].split('\n')[1:] + for id, option in enumerate(options): + option_id = chr(ord('A') + id) + '.' + if option.find(option_id) >= 0: + input_item[chr(ord('A') + id)] = option[option.find(option_id) + len(option_id):].strip('. \n') + return extract_answer_from_item(model, input_item, dataset_name)['opt'] + + +def extract_characters_regex(s): + s = s.strip() + answer_prefixes = [ + 'The best answer is', + 'The correct answer is', + 'The answer is', + 'The answer', + 'The best option is' + 'The correct option is', + 'Best answer:' + 'Best option:', + 'Answer:', + 'Option:', + ] + for answer_prefix in answer_prefixes: + s = s.replace(answer_prefix, '') + + if len(s.split()) > 10 and not re.search('[ABCD]', s): + return '' + matches = re.search(r'[ABCD]', s) + if matches is None: + return '' + return matches[0] diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/vdc.py b/VLMEvalKit-sudoku/vlmeval/dataset/vdc.py new file mode 100644 index 0000000000000000000000000000000000000000..75e1051bcd57b36180526a6ee912b7c3fc306a7b --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/vdc.py @@ -0,0 +1,425 @@ +# flake8: noqa +from huggingface_hub import snapshot_download +from ..smp import * +from ..smp.file import get_intermediate_file_path, get_file_extension +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..utils import track_progress_rich +import random +import json +import ast +from glob import glob + +FAIL_MSG = 'Failed to obtain answer via API.' + +camera_caption_prompts = [ + "Summary of the view shot, camera movement and changes in shooting angles in the sequence of video frames.", + "Describe the camera movements in these frames.", + "What are the camera angles and movements throughout the video?", + "Summarize the camera actions and perspectives.", + "Describe any camera zooms, pans, or angle changes.", + "What camera movements are present in these frames?", + "Describe the camera's movements, including pans, zooms, and angle changes in these frames.", + "Summarize the camera actions and changes in shooting angles during the video.", + "Provide a detailed description of the camera's movements and perspectives.", + "Describe the camera's actions and how it follows the main subject.", + "What are the camera movements and angle shifts in these frames?", + "Given these equally spaced frames, provide a comprehensive description of the camera's movements, including any pans, zooms, and changes in shooting angles.", + "Describe the camera's movements and angles in detail, explaining how it follows the main subject and changes perspectives.", + "Based on these frames, provide a detailed description of the camera's actions, including any pans, zooms, angle shifts, and how it captures the scene.", + "Using these frames, describe the camera's movements, including its tracking of the main subject, changes in angles, and any zooms or pans.", + "Provide an elaborate description of the camera movements, covering pans, zooms, and changes in shooting angles as shown in these frames." +] + +detailed_caption_prompts = [ + "The images are given containing equally spaced video frames. Please imagine the video based on the sequence of frames, and provide a faithfully detailed description of this video in more than three sentences.", + "You are given a sequence of equally spaced video frames. Based on these frames, imagine the full video and provide a detailed description of what is happening in more than three sentences.", + "The following set contains equally spaced video frames. Imagine the video from which these frames were taken and describe it in detail in at least three sentences.", + "Below are equally spaced frames from a video. Use these frames to visualize the entire video and provide a detailed description in more than three sentences.", + "A sequence of equally spaced video frames is presented. Please imagine the full video and write a faithfully detailed description of the events in more than three sentences.", + "The images provided include equally spaced frames from a video. Based on these frames, imagine the video and describe it comprehensively in at least three sentences.", + "You are given equally spaced frames from a video. Use these frames to envision the entire video and provide a detailed description of the events in more than three sentences.", + "The sequence includes equally spaced frames from a video. Imagine the full video based on these frames and provide a detailed description in more than three sentences.", + "The provided images contain equally spaced frames from a video. Visualize the video from these frames and describe it in detail in more than three sentences.", + "Here are equally spaced frames from a video. Based on these frames, imagine the video and provide a detailed, faithful description of it in more than three sentences.", + "The set of images includes equally spaced video frames. Please imagine the video these frames come from and describe it comprehensively in at least three sentences.", + "Describe the video based on these frames in a few sentences.", + "What is happening in the video shown in these frames?", + "Explain the video using these frames.", + "Imagine the video from these frames and describe it in detail in a few sentences.", + "Based on these frames, provide a narrative of the video in more than three sentences.", + "Describe the events in the video shown by these frames in at least three sentences.", + "Visualize the video from these frames and explain what is happening in more than three sentences.", + "Describe the sequence of events in the video depicted by these frames in a detailed manner.", + "Given these equally spaced frames, imagine the entire video and provide a detailed description of the events, including the setting, characters, and actions, in more than three sentences.", + "Visualize the video based on these frames and write a comprehensive description of what happens, describing the beginning, middle, and end in at least three sentences.", + "Using these frames as a reference, imagine the full video and provide a thorough description of the plot, including key details and actions, in more than three sentences.", + "Based on the sequence of these frames, describe the entire video in detail, mentioning important aspects such as the context, movements, and transitions in more than three sentences.", + "Imagine the video that corresponds to these frames and provide an elaborate description, covering the storyline, visual elements, and any notable features in at least three sentences." +] + +background_caption_prompts = [ + "The images are given containing equally spaced video frames.Summary of the background. This should also include the objects, location, weather, and time.", + "Describe the background, including objects, location, weather, and time.", + "Summarize the background setting of the video based on these frames.", + "What is the environment like in these frames?", + "Describe the location and weather in these frames.", + "What background objects and settings are visible in these frames?", + "Summarize the background of the video, including details about the location, objects, weather, and time.", + "Describe the environment shown in these frames, covering objects, location, weather, and time.", + "Provide a detailed background description based on these frames, mentioning objects, location, weather, and time.", + "Explain the setting of the video, focusing on the background elements like objects, location, weather, and time.", + "Describe the overall environment in these frames, including details about objects, location, weather, and time.", + "Given these equally spaced frames, provide a comprehensive background description, covering the objects, location, weather, and time of day.", + "Imagine the environment from these frames and write a detailed description of the background, including objects, location, weather, and time.", + "Based on these frames, describe the setting in detail, mentioning the objects present, the specific location, the weather conditions, and the time of day.", + "Provide an elaborate background description based on these frames, covering all aspects of the environment such as objects, location, weather, and time.", + "Using these frames as a reference, give a thorough description of the background, including details about the objects, location, weather, and time." +] + +short_caption_prompts = [ + "Write a one-sentence summary of the video.", + "Summarize the video in one concise sentence.", + "Provide a brief description of the video in one sentence.", + "Describe the main action in the video in one sentence.", + "What is the video about? Summarize it in one sentence.", + "In one sentence, summarize the key visual elements of the video.", + "Provide a one-sentence summary that captures the main subject and action in the video.", + "Write a concise one-sentence description that encapsulates the essence of the video.", + "Describe the main theme or action of the video in a single sentence.", + "What is happening in the video? Provide a one-sentence summary.", + "Given these frames, write a brief one-sentence summary that captures the essence of the video's visual and artistic style.", + "Summarize the key visual and thematic elements of the video in one concise sentence.", + "Provide a one-sentence description that highlights the main subject and action depicted in the video.", + "In one sentence, describe the primary visual and artistic elements of the video.", + "Write a concise one-sentence summary that encapsulates the main action and visual style of the video.", + "Briefly one-sentence Summary of the visual, Photographic and artistic style." +] + +main_object_caption_prompts = [ + "Description of the main subject actions or status sequence. This suggests including the main subjects (person, object, animal, or none) and their attributes, their action, their position, and movements during the video frames.", + "Describe the main subject's actions and movements.", + "What is the main object doing in these frames?", + "Summarize the primary subject's attributes and actions.", + "Describe the main subject's position and movements.", + "What actions does the main object take in these frames?", + "Describe the main subject, including their attributes and movements throughout the video.", + "Provide a detailed description of the main object's actions and positions in these frames.", + "Summarize the main subject's actions, attributes, and movements during the video.", + "Describe the primary subject's movements and actions in detail.", + "What are the main object's attributes and how do they move throughout the video?", + "Given these equally spaced frames, provide a comprehensive description of the main subject, including their attributes, actions, positions, and movements.", + "Describe the primary object or subject in the video, detailing their attributes, actions, positions, and movements in these frames.", + "Based on these frames, provide a detailed description of the main subject, including their attributes, actions, positions, and how they navigate through the video.", + "Using these frames, describe the main subject's attributes, actions, and movements, detailing their positions and how they interact with the environment.", + "Provide an elaborate description of the main object in the video, covering their attributes, actions, positions, and movements as shown in these frames." +] + + +class VDC(VideoBaseDataset): + + MD5 = '' + + TYPE = 'Video-VQA' + + def __init__(self, dataset='VDC', pack=False, nframe=0, fps=-1, subset='all', limit=1.0): + super().__init__(dataset=dataset, pack=pack, nframe=nframe, fps=fps) + + if subset == 'all': + pass + elif subset == 'breakpoint': + self.data = self.data[self.data['caption_type'] == 'breakpoint'] + elif subset == 'short': + self.data = self.data[self.data['caption_type'] == 'short'] + elif subset == 'detailed': + self.data = self.data[self.data['caption_type'] == 'detailed'] + elif subset == 'background': + self.data = self.data[self.data['caption_type'] == 'background'] + elif subset == 'main_object': + self.data = self.data[self.data['caption_type'] == 'main_object'] + else: + raise ValueError(f'Invalid subset: {subset}') + + if limit <= 1.0 and limit > 0: + sample_num = int(limit * len(self.data)) + self.data = self.data.iloc[:sample_num] + elif limit > 1.0 and limit < len(self.data): + self.data = self.data.iloc[:limit] + else: + raise ValueError(f'Invalid limit: {limit}') + + @classmethod + def supported_datasets(cls): + return ['VDC'] + + def prepare_dataset(self, dataset_name='VDC', repo_id='Enxin/VLMEval-VDC'): + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + if md5(data_file) != self.MD5: + return False + data = load(data_file) + for video_pth in data['video']: + if not osp.exists(osp.join(pth, 'videos', video_pth)): + return False + return True + + if os.path.exists(repo_id): + dataset_path = repo_id + else: + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + cache_path = snapshot_download(repo_id=repo_id, repo_type="dataset") + if not glob(osp.join(cache_path, "video")): + tar_files = glob(osp.join(cache_path, "**/*.tar*"), recursive=True) + + def untar_video_data(tar_file, cache_dir): + import tarfile + with tarfile.open(tar_file, "r") as tar_ref: + tar_ref.extractall(cache_dir) + print(f"Extracted all files from {tar_file} to {cache_dir}") + + def concat_tar_parts(tar_parts, output_tar): + with open(output_tar, "wb") as out_tar: + from tqdm import tqdm + for part in tqdm(sorted(tar_parts)): + with open(part, "rb") as part_file: + out_tar.write(part_file.read()) + print(f"Concatenated parts {tar_parts} into {output_tar}") + + tar_parts_dict = {} + + # Group tar parts together + for tar_file in tar_files: + base_name = tar_file.split(".tar")[0] + if base_name not in tar_parts_dict: + tar_parts_dict[base_name] = [] + tar_parts_dict[base_name].append(tar_file) + + # Concatenate and untar split parts + for base_name, parts in tar_parts_dict.items(): + print(f"Extracting following tar files: {parts}") + output_tar = base_name + ".tar" + if not osp.exists(output_tar): + print('Start concatenating tar files') + + concat_tar_parts(parts, output_tar) + print('Finish concatenating tar files') + + if not osp.exists(osp.join(cache_path, osp.basename(base_name))): + untar_video_data(output_tar, cache_path) + dataset_path = cache_path + self.video_path = osp.join(dataset_path, 'videos/') + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + return dict(data_file=data_file, root=osp.join(dataset_path, 'video')) + + def build_prompt_pack(self, line): + if isinstance(line, int): + assert line < len(self) + video = self.videos[line] + elif isinstance(line, pd.Series): + video = line['video'] + elif isinstance(line, str): + video = line + + frames = self.save_video_frames(video) + message = [] + for im in frames: + message.append(dict(type='image', value=im)) + + if self.data['caption_type'] == 'short': + prompt = random.choice(short_caption_prompts) + elif self.data['caption_type'] == 'detailed': + prompt = random.choice(detailed_caption_prompts) + elif self.data['caption_type'] == 'background': + prompt = random.choice(background_caption_prompts) + elif self.data['caption_type'] == 'main_object': + prompt = random.choice(main_object_caption_prompts) + else: + prompt = random.choice(camera_caption_prompts) + message.append(dict(type='text', value=prompt, role='user')) + return message + + def build_prompt_nopack(self, line, video_llm): + """Build prompt for a single line without packing""" + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + if line['caption_type'] == 'short': + prompt = random.choice(short_caption_prompts) + elif line['caption_type'] == 'detailed': + prompt = random.choice(detailed_caption_prompts) + elif line['caption_type'] == 'background': + prompt = random.choice(background_caption_prompts) + elif line['caption_type'] == 'main_object': + prompt = random.choice(main_object_caption_prompts) + else: + prompt = random.choice(camera_caption_prompts) + + if video_llm: + video_path = os.path.join(self.video_path, line['video']) + return [ + dict(type='video', value=video_path), + dict(type='text', value=prompt) + ] + else: + frames = self.save_video_frames(os.path.splitext(line['video'])[0]) + message = [] + for im in frames: + message.append(dict(type='image', value=im)) + message.append(dict(type='text', value=prompt)) + return message + + def build_prompt(self, line, video_llm): + if self.pack and not video_llm: + return self.build_prompt_pack(line) + else: + return self.build_prompt_nopack(line, video_llm) + + @staticmethod + def remove_side_quote(s, syms=[',', '"', "'"]): + if np.all([x in syms for x in s]): + return '' + while s[0] in syms: + s = s[1:] + while s[-1] in syms: + s = s[:-1] + return s + + @staticmethod + def robust_json_load(s): + try: + jsons = list(extract_json_objects(s)) + assert len(jsons) == 1 + return jsons[0] + except: + if '{' in s and s.find('{') == s.rfind('{'): + sub_str = s[s.find('{') + 1:].strip() + lines = sub_str.split('\n') + res = {} + for l in lines: + l = l.strip() + if ': ' in l: + key = l.split(': ')[0].strip() + val = l.split(': ')[1].strip() + key = VDC.remove_side_quote(key) + val = VDC.remove_side_quote(val) + if len(key) and len(val): + res[key] = val + return res + return None + + def load_pack_answers(self, data_raw): + vstats = defaultdict(lambda: 0) + data = defaultdict(lambda: {}) + + for k in data_raw: + ans = data_raw[k].strip() + if FAIL_MSG in ans: + vstats['GEN_FAIL'] += 1 + continue + res = self.robust_json_load(ans) + if res is not None: + data[k] = res + vstats['PARSE_OK'] += 1 + else: + vstats['PARSE_FAIL'] += 1 + + # return data + meta = cp.deepcopy(self.data) + lt = len(meta) + prediction = [] + for i in range(lt): + line = meta.iloc[i] + vid = line['video'] + idx = str(line['index']) + prediction.append(data[vid][idx] if idx in data[vid] else None) + meta['prediction'] = prediction + vstats['VALIDQ'] = len([x for x in prediction if x is not None]) + vstats['INVALIDQ'] = len([x for x in prediction if x is None]) + return meta, vstats + + # It returns a dictionary + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + from .utils.vdc import get_dimension_rating, prepare_response_prompt, prepare_score_prompt, SYSTEM_CAL_SCORE_PROMPT, SYSTEM_GENER_PRED_PROMPT + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' + judge = judge_kwargs['model'] + nproc = judge_kwargs.pop('nproc', 4) + _ = judge_kwargs.pop('verbose', None) + _ = judge_kwargs.pop('retry', None) + + response_file = get_intermediate_file_path(eval_file, f'_{judge}_response', 'pkl') + tmp_file = get_intermediate_file_path(eval_file, f'_{judge}_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, f'_{judge}_rating', 'json') + score_file = get_intermediate_file_path(eval_file, f'_{judge}_score') + + model = build_judge(**judge_kwargs) + + if not osp.exists(score_file): + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + + expanded_data = [] + for idx, row in data.iterrows(): + try: + questions = ast.literal_eval(row['question']) if isinstance(row['question'], str) else row['question'] + for q_dict in questions: + new_row = row.copy() + new_row['question'] = q_dict['question'] + new_row['answer'] = q_dict['answer'] + expanded_data.append(new_row) + except Exception as e: + print(f"Error parsing questions for row {idx}") + print(f"Error message: {str(e)}") + continue + + expanded_df = pd.DataFrame(expanded_data).reset_index(drop=True) + + data_un = expanded_df[~expanded_df['index'].isin(res)] + data_un = data_un[~pd.isna(data_un['prediction'])] + lt = len(data_un) + + response_prompts = [prepare_response_prompt(data_un.iloc[i]) for i in range(lt)] + indices = [data_un.iloc[i]['index'] for i in range(lt)] + + model.system_prompt = SYSTEM_GENER_PRED_PROMPT + if len(response_prompts): + print(f"Processing {len(response_prompts)} valid prompts out of {lt} total items") + _ = track_progress_rich( + model.generate, + response_prompts, + keys=indices, + save=response_file, + nproc=nproc, + chunksize=nproc + ) + + pred_map = load(response_file) + data_un['pred_response'] = [pred_map[idx] for idx in data_un['index']] + score_prompts = [prepare_score_prompt(data_un.iloc[i]) for i in range(lt)] + model.system_prompt = SYSTEM_CAL_SCORE_PROMPT + if len(score_prompts): + _ = track_progress_rich( + model.generate, + score_prompts, + keys=indices, + save=tmp_file, + nproc=nproc, + chunksize=nproc + ) + + score_map = load(tmp_file) + data['score'] = [score_map[idx] for idx in data['index']] + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/video_base.py b/VLMEvalKit-sudoku/vlmeval/dataset/video_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a1854be48d78f6c7604f2453a9c8aa7f45533b7d --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/video_base.py @@ -0,0 +1,147 @@ +from abc import abstractmethod +from ..smp import * + + +class VideoBaseDataset: + + MODALITY = 'VIDEO' + + def __init__(self, + dataset='MMBench-Video', + pack=False, + nframe=0, + fps=-1): + try: + import decord + except Exception as e: + logging.critical(f'{type(e)}: {e}') + logging.critical('Please install decord via `pip install decord`.') + + self.dataset_name = dataset + ret = self.prepare_dataset(dataset) + assert ret is not None + lmu_root = LMUDataRoot() + self.frame_root = osp.join(lmu_root, 'images', dataset) + os.makedirs(self.frame_root, exist_ok=True) + self.frame_tmpl = 'frame-{}-of-{}.jpg' + self.frame_tmpl_fps = 'frame-{}-of-{}-{}fps.jpg' + + self.data_root = ret['root'] + self.data_file = ret['data_file'] + self.data = load(self.data_file) + if 'index' not in self.data: + self.data['index'] = np.arange(len(self.data)) + + assert 'question' in self.data and 'video' in self.data + videos = list(set(self.data['video'])) + videos.sort() + self.videos = videos + self.pack = pack + self.nframe = nframe + self.fps = fps + if self.fps > 0 and self.nframe > 0: + raise ValueError('fps and nframe should not be set at the same time') + if self.fps <= 0 and self.nframe <= 0: + raise ValueError('fps and nframe should be set at least one valid value') + + def __len__(self): + return len(self.videos) if self.pack else len(self.data) + + def __getitem__(self, idx): + if self.pack: + assert idx < len(self.videos) + sub_data = self.data[self.data['video'] == self.videos[idx]] + return sub_data + else: + assert idx < len(self.data) + return dict(self.data.iloc[idx]) + + def frame_paths(self, video): + frame_root = osp.join(self.frame_root, video) + os.makedirs(frame_root, exist_ok=True) + return [osp.join(frame_root, self.frame_tmpl.format(i, self.nframe)) for i in range(1, self.nframe + 1)] + + def frame_paths_fps(self, video, num_frames): + frame_root = osp.join(self.frame_root, video) + os.makedirs(frame_root, exist_ok=True) + return [osp.join(frame_root, + self.frame_tmpl_fps.format(i, num_frames, self.fps)) for i in range(1, num_frames + 1)] + + def save_video_frames(self, video): + import decord + if self.fps > 0: + vid_path = osp.join(self.data_root, video + '.mp4') + vid = decord.VideoReader(vid_path) + + # 计算视频的总帧数和总时长 + total_frames = len(vid) + video_fps = vid.get_avg_fps() + total_duration = total_frames / video_fps + + # 计算需要提取的总帧数 + required_frames = int(total_duration * self.fps) + + # 计算提取帧的间隔 + step_size = video_fps / self.fps + + # 计算提取帧的索引 + indices = [int(i * step_size) for i in range(required_frames)] + + # 提取帧并保存 + frame_paths = self.frame_paths_fps(video, len(indices)) + flag = np.all([osp.exists(p) for p in frame_paths]) + if flag: + return frame_paths + + lock_path = osp.join(self.frame_root, video + '.lock') + with portalocker.Lock(lock_path, 'w', timeout=30): + if np.all([osp.exists(p) for p in frame_paths]): + return frame_paths + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + return frame_paths + + else: + frame_paths = self.frame_paths(video) + flag = np.all([osp.exists(p) for p in frame_paths]) + if flag: + return frame_paths + lock_path = osp.join(self.frame_root, video + '.lock') + with portalocker.Lock(lock_path, 'w', timeout=30): + if np.all([osp.exists(p) for p in frame_paths]): + return frame_paths + vid_path = osp.join(self.data_root, video + '.mp4') + vid = decord.VideoReader(vid_path) + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + return frame_paths + + # Return a list of dataset names that are supported by this class, can override + @classmethod + def supported_datasets(cls): + return ['MMBench-Video', 'Video-MME', 'MVBench', 'MVBench_MP4', + 'LongVideoBench', 'WorldSense', 'VDC', 'MovieChat1k'] + + # Given the prediction file, return the evaluation results in the format of a dictionary or pandas dataframe + @abstractmethod + def evaluate(self, eval_file, **judge_kwargs): + pass + + @abstractmethod + def build_prompt(self, idx): + pass + + @abstractmethod + def prepare_dataset(self, dataset): + # The prepare_dataset function should return a dictionary containing: + # `root` (directory that containing video files) + # `data_file` (the TSV dataset file) + pass diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/video_concat_dataset.py b/VLMEvalKit-sudoku/vlmeval/dataset/video_concat_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf3e8227c4d250e95d7180935585e7b0f33614d --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/video_concat_dataset.py @@ -0,0 +1,85 @@ +from ..smp import * +from ..smp.file import get_intermediate_file_path +from .video_base import VideoBaseDataset + + +class ConcatVideoDataset(VideoBaseDataset): + # This dataset takes multiple dataset names as input and aggregate them into a single dataset. + # Each single dataset should not have a field named `SUB_DATASET` + + DATASET_SETS = {} + + def __init__(self, dataset, **kwargs): + from . import build_dataset + datasets = self.DATASET_SETS[dataset] + self.dataset_map = {} + # The name of the compliation + self.dataset_name = dataset + self.datasets = datasets + self.nframe = kwargs.get('nframe', 0) + self.fps = kwargs.get('fps', -1) + for dname in datasets: + dataset = build_dataset(dname, **kwargs) + assert dataset is not None, dataset + self.dataset_map[dname] = dataset + TYPES = [x.TYPE for x in self.dataset_map.values()] + MODALITIES = [x.MODALITY for x in self.dataset_map.values()] + # assert np.all([x == TYPES[0] for x in TYPES]), (datasets, TYPES) + assert np.all([x == MODALITIES[0] for x in MODALITIES]), (datasets, MODALITIES) + self.TYPE = TYPES + self.MODALITY = MODALITIES[0] + data_all = [] + for dname in datasets: + data = self.dataset_map[dname].data + data['SUB_DATASET'] = [dname] * len(data) + data_all.append(data) + + data = pd.concat(data_all) + data['original_index'] = data.pop('index') + data['index'] = np.arange(len(data)) + self.data = data + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + line = self.data.iloc[line] + idx = line['original_index'] + dname = line['SUB_DATASET'] + org_data = self.dataset_map[dname].data + org_line = cp.deepcopy(org_data[org_data['index'] == idx]).iloc[0] + return self.dataset_map[dname].build_prompt(org_line, video_llm) + + def dump_image(self, line): + # Assert all images are pre-dumped + assert 'image' not in line + assert 'image_path' in line + tgt_path = toliststr(line['image_path']) + return tgt_path + + @classmethod + def supported_datasets(cls): + return [] # list(cls.DATASET_SETS) + + def evaluate(self, eval_file, **judge_kwargs): + # First, split the eval_file by dataset + data_all = load(eval_file) + for dname in self.datasets: + tgt = eval_file.replace(self.dataset_name, dname) + data_sub = data_all[data_all['SUB_DATASET'] == dname] + data_sub.pop('index') + data_sub['index'] = data_sub.pop('original_index') + data_sub.pop('SUB_DATASET') + dump(data_sub, tgt) + # Then, evaluate each dataset separately + results_all = {} + for dname in self.datasets: + tgt = eval_file.replace(self.dataset_name, dname) + res = self.dataset_map[dname].evaluate(tgt, **judge_kwargs) + results_all.update(res) + + result = pd.DataFrame(results_all, index=['success', 'overall']) + result = result.T + for idx, item in result.iterrows(): + result.loc[idx, 'acc'] = round(item['success'] / item['overall'] * 100, 1) + score_file = get_intermediate_file_path(eval_file, '_acc', 'csv') + dump(result, score_file) + return result diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/visfactor.py b/VLMEvalKit-sudoku/vlmeval/dataset/visfactor.py new file mode 100644 index 0000000000000000000000000000000000000000..6b8313fbd3c2b0fd972b4667bbf4703e4b91a348 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/visfactor.py @@ -0,0 +1,152 @@ +import re +from vlmeval import * +from .image_base import ImageBaseDataset +from ..smp.file import get_intermediate_file_path + + +class VisFactor(ImageBaseDataset): + TYPE = 'VQA' + + DATASET_URL = { + 'VisFactor': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor.tsv', + 'VisFactor_CoT': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor.tsv', + 'VisFactor_GE': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GE.tsv', + 'VisFactor_GE_CoT': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GE.tsv', + 'VisFactor_GN': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GN.tsv', + 'VisFactor_GN_CoT': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GN.tsv', + 'VisFactor_GH': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GH.tsv', + 'VisFactor_GH_CoT': 'https://opencompass.openxlab.space/utils/VLMEval/VisFactor_GH.tsv', + } + + DATASET_MD5 = { + 'VisFactor': 'a069bcd8eb529e1d8c66e4cd7e279d13', + 'VisFactor_CoT': 'a069bcd8eb529e1d8c66e4cd7e279d13', + 'VisFactor_GE': '7e1377b46faff392409a7d4e56688dba', + 'VisFactor_GE_CoT': '7e1377b46faff392409a7d4e56688dba', + 'VisFactor_GN': '34bec098b47f87a8a6239a68f19b9ec8', + 'VisFactor_GN_CoT': '34bec098b47f87a8a6239a68f19b9ec8', + 'VisFactor_GH': '03c902ea44da8469814a8c1933baa923', + 'VisFactor_GH_CoT': '03c902ea44da8469814a8c1933baa923', + } + + def replace_additional_tags(self, text, additional): + def replacer(match): + index = int(match.group(1)) + if 0 <= index < len(additional): + return additional[index] + else: + return match.group(0) + return re.sub(r"", replacer, text) + + def split_image_tags(self, text): + parts = re.split(r'()', text) + return [part for part in parts if part != ''] + + def extract_last_json_answer(self, s): + pattern = r'\{\s*"answer"\s*:\s*(.+?)\s*\}' + matches = list(re.finditer(pattern, s)) + if not matches: + return '' + + raw_value = matches[-1].group(1).strip() + + if (raw_value.startswith('"') and raw_value.endswith('"')) or \ + (raw_value.startswith("'") and raw_value.endswith("'")): + raw_value = raw_value[1:-1] + return raw_value + + def extract_last_numbers(self, s): + return [num for num in re.findall(r'\d+', s)] + + def extract_last_uppercase_letter(self, s): + for char in reversed(s): + if char.isupper(): + return char + return None + + def build_prompt(self, line): + msgs = line['question'].replace('
', '\n') + image_paths = self.dump_image(line) + + if str(line['additional']) != 'nan': + additional = str(line['additional']).replace('
', '\n').split(';') + msgs = self.replace_additional_tags(msgs, additional) + + if 'cot' in self.dataset_name.lower(): + msgs = msgs.replace( + 'Output: Respond', + 'Output: Solve the problem step-by-step. First, reason through the problem clearly. At the end, respond' + ) + msgs = self.split_image_tags(msgs) + + for i in range(len(msgs)): + if msgs[i][0] != '<': + msgs[i] = dict(type="text", value=msgs[i]) + else: + msgs[i] = dict(type="image", value=image_paths[int(msgs[i][-2])]) + + return msgs + + def evaluate(self, eval_file, **judge_kwargs): + data = load(eval_file) + subtests = sorted(set([str(i) for i in data['category_id']])) + accuracy = {key: {} for key in subtests} + + for index, row in data.iterrows(): + cid = str(row['category_id']) + prediction = self.extract_last_json_answer(str(row['prediction'])) + answer = str(row['answer']) + additional = str(row['additional']) + + if (cid in ['CF1', 'CF2', 'MV1', 'MV2', 'MV3', 'P3', 'RL2', 'S1', 'S2', 'SS2', 'VZ1', 'VZ2']) or \ + (cid == 'VZ3' and not additional.isdigit()): + if prediction.lower() in ['t', 'y', '1', 'true', 'yes']: + data.at[index, 'pred'] = 'T' + elif prediction.lower() in ['f', 'n', '0', 'false', 'no']: + data.at[index, 'pred'] = 'F' + else: + data.at[index, 'pred'] = '' + data.at[index, 'correct'] = (data.at[index, 'pred'] == answer) + elif cid in ['CS1', 'CS2', 'CS3']: + data.at[index, 'pred'] = prediction + data.at[index, 'correct'] = (data.at[index, 'pred'].lower() in [i.lower() for i in answer.split(',')]) + elif cid in ['CF3', 'I3', 'MA1', 'SS3', 'VZ3']: + if prediction == '': + prediction = str(row['prediction']) + if cid == 'VZ3': + prediction = self.extract_last_uppercase_letter(prediction) + elif cid == 'CF3': + prediction = self.extract_last_numbers(prediction) + prediction = '' if len(prediction) < 2 else f'({prediction[-2]}, {prediction[-1]})' + else: + prediction = self.extract_last_numbers(prediction) + prediction = '' if len(prediction) < 1 else prediction[-1] + data.at[index, 'pred'] = prediction + data.at[index, 'correct'] = (data.at[index, 'pred'] == answer) + + for index, row in data.iterrows(): + cid = str(row['category_id']) + eid = str(row['eval_index']) + if eid not in accuracy[cid]: + accuracy[cid][eid] = [row['correct']] + else: + accuracy[cid][eid].append(row['correct']) + + for subtest in accuracy: + for eval_index in accuracy[subtest]: + accuracy[subtest][eval_index] = 1 if all(accuracy[subtest][eval_index]) else 0 + + for subtest in accuracy: + results = [accuracy[subtest][eval_index] for eval_index in accuracy[subtest]] + accuracy[subtest] = sum(results) / len(results) + + accuracy['ALL'] = sum([accuracy[s] for s in accuracy]) / len([accuracy[s] for s in accuracy]) + + verbose_file = get_intermediate_file_path(eval_file, '_verbose') + dump(data, verbose_file) + + score_df = d2df(accuracy) + score_file = get_intermediate_file_path(eval_file, '_acc') + dump(score_df, score_file) + + return accuracy diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/vl_rewardbench.py b/VLMEvalKit-sudoku/vlmeval/dataset/vl_rewardbench.py new file mode 100644 index 0000000000000000000000000000000000000000..ce8b397a80524137a2c5a7c63c7ef2346b9d1f76 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/vl_rewardbench.py @@ -0,0 +1,173 @@ +from ast import literal_eval + +from .image_base import ImageBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +from ..smp import * +from ..utils import track_progress_rich + + +LLM_PARSE_ANSWER_PROMPT = ''' +You are given a pairwise judgement for two responses. Please return the better response according to the judgement. +Return the Answer X ONLY. e.g., Answer 1 or Answer 2. + +Judgement: {judgement} +''' + + +PROMPT_TEMPLATE = '''\ +You are a highly capable multimodal AI assistant tasked with evaluating answers to visual questions. +Please analyze the following image and question, then determine which of the two provided answers is better. + +Question: {query} + +Answer 1: {answer_0} + +Answer 2: {answer_1} + +Please evaluate both answers based on the following criteria: +1. Accuracy: How well does the answer align with the visual information in the image? +2. Completeness: Does the answer fully address all aspects of the question? +3. Clarity: Is the answer easy to understand and well-articulated? +4. Relevance: Does the answer directly relate to the question and the image? + +After your evaluation, please: +1. Explain your reasoning for each criterion. +2. Provide an overall judgment on which answer is better (Answer 1 or Answer 2).\ +For example: Overall Judgment: Answer X is better. + +Your response should be structured and detailed, \ +demonstrating your understanding of both the visual and textual elements of the task.''' + + +def get_score(line, parsed_response, random_number): + gt_ans = line['human_ranking'].index(0 if random_number == 0 else 1) + 1 + if 'Answer 1'.lower() in parsed_response.lower(): + pred = 1 + elif 'Answer 2'.lower() in parsed_response.lower(): + pred = 2 + else: # failed + pred = 'None' # random.choice([1, 2]) + + if pred == gt_ans: + return 1.0 + else: + return 0.0 + + +def VLRewardBench_eval_answer(model, line): + response = toliststr(line['response']) + random_number = sum(len(res) for res in response) % 2 + + prompt = LLM_PARSE_ANSWER_PROMPT.format(judgement=line['prediction']) + messages = [dict(type='text', value=prompt)] + + resp = model.generate(messages) + score = get_score(line, resp, random_number) + + if score is None: + return 'Unknown' + return score + + +class VLRewardBench(ImageBaseDataset): + TYPE = 'VQA' + DATASET_URL = { + 'VL-RewardBench': 'https://huggingface.co/datasets/MMInstruction/VL-RewardBench/resolve/main/vl_rewardbench.tsv' + } + DATASET_MD5 = {'VL-RewardBench': '1d2676f4ab4a5f755019ec0af2b28189'} + + # Given one data record, return the built prompt (a multi-modal message), can override + def build_prompt(self, line): + if isinstance(line, int): + line = self.data.iloc[line] + tgt_path = self.dump_image(line) # save image to local + question = line['question'] + msgs = [] + if isinstance(tgt_path, list): + msgs.extend([dict(type='image', value=p) for p in tgt_path]) + else: + msgs = [dict(type='image', value=tgt_path)] + + response = toliststr(line['response']) + random_number = sum(len(res) for res in response) % 2 + if random_number == 1: + # randomly shuffle the order of the responses + response = response[::-1] + query_prompt = PROMPT_TEMPLATE.format( + query=question, answer_0=response[0], answer_1=response[1] + ) + msgs = msgs + [dict(type='text', value=query_prompt)] + return msgs + + # It returns a DataFrame + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + model = judge_kwargs['model'] + storage = get_intermediate_file_path(eval_file, f'_{model}') + score_file = get_intermediate_file_path(eval_file, f'_{model}_score', 'csv') + tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') + nproc = judge_kwargs.pop('nproc', 4) + + if not osp.exists(storage): + raw_data = VLRewardBench('VL-RewardBench').data + data = load(eval_file) + data['prediction'] = [str(x) for x in data['prediction']] + data['human_ranking'] = [literal_eval(x) for x in raw_data['answer']] + + judge_kwargs['temperature'] = 0 + judge_kwargs['timeout'] = 60 + model = build_judge(max_tokens=128, **judge_kwargs) + + assert model.working(), ( + 'VLRewardBench evaluation requires a working OPENAI API\n' + + DEBUG_MESSAGE + ) + + lt = len(data) + lines = [data.iloc[i] for i in range(lt)] + tups = [(model, line) for line in lines] + indices = [line['index'] for line in lines] + + ans = load(tmp_file) if osp.exists(tmp_file) else {} + tups = [x for x, i in zip(tups, indices) if i not in ans] + indices = [i for i in indices if i not in ans] + + if len(indices): + new_results = track_progress_rich( + VLRewardBench_eval_answer, + tups, + nproc=nproc, + chunksize=nproc, + keys=indices, + save=tmp_file, + ) + ans = load(tmp_file) + for k, v in zip(indices, new_results): + ans[k] = v + + data['score'] = [ans[idx] for idx in data['index']] + # data.pop('image') + dump(data, storage) + + data = load(storage) + lt = len(data) + + category_scores = defaultdict(lambda: 0) + category_cnt = defaultdict(lambda: 0) + scores = defaultdict(lambda: 0) + for i in range(lt): + item = data.iloc[i] + category_scores[item['category']] += item['score'] + category_cnt[item['category']] += 1 + # calculate the average score for each category + for k, v in category_scores.items(): + scores[k] = v / category_cnt[k] + # calculate category macro accuracy (average across categories) + scores['Macro Accuracy'] = sum(scores.values()) / len(scores) + # calculate the total average score + scores['Overall Consistency'] = sum(category_scores.values()) / lt + + scores = {k: [v] for k, v in scores.items()} + scores = pd.DataFrame(scores) + dump(scores, score_file) + return scores diff --git a/VLMEvalKit-sudoku/vlmeval/dataset/worldsense.py b/VLMEvalKit-sudoku/vlmeval/dataset/worldsense.py new file mode 100644 index 0000000000000000000000000000000000000000..fe59c65ab06c14a64a340f44cb6a13cea1e25c1c --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/dataset/worldsense.py @@ -0,0 +1,339 @@ +from huggingface_hub import snapshot_download +from ..smp import * +from .video_base import VideoBaseDataset +from .utils import build_judge, DEBUG_MESSAGE +import json + + +FAIL_MSG = 'Failed to obtain answer via API.' + + +class WorldSense(VideoBaseDataset): + + MD5 = 'bfc25490be4080aa5494b883370b6b1f' + + BASE_SYS = 'Carefully watch this video and pay attention to every detail. ' + SYS = BASE_SYS + 'Based on your observations, select the best option that accurately addresses the question.' + + FRAMES_TMPL_NOSUB = """ +These are the frames of a video. \ +Select the best answer to the following multiple-choice question based on the video. \ +Respond with only the letter (A, B, C, or D) of the correct option. +""" + + FRAMES_TMPL_SUB = """ +These are the frames of a video. \ +This video's subtitles are listed below: +{} +Select the best answer to the following multiple-choice question based on the video. \ +Respond with only the letter (A, B, C, or D) of the correct option. +""" + + FRAMES_TMPL_AUDIO = """ +These are the frames of a video and the corresponding audio. \ +Select the best answer to the following multiple-choice question based on the video. \ +Respond with only the letter (A, B, C, or D) of the correct option. +""" + + TYPE = 'Video-MCQ' + + def __init__(self, dataset='WorldSense', use_subtitle=False, use_audio=False, nframe=0, fps=-1): + super().__init__(dataset=dataset, nframe=nframe, fps=fps) + self.use_subtitle = use_subtitle + self.use_audio = use_audio + self.dataset_name = dataset + + assert not (self.use_subtitle and self.use_audio), 'Cannot use both subtitle and audio at the same time.' + + @classmethod + def supported_datasets(cls): + return ['WorldSense'] + + def prepare_dataset(self, dataset_name='WorldSense', repo_id='honglyhly/WorldSense'): + + def check_integrity(pth): + data_file = osp.join(pth, f'{dataset_name}.tsv') + + if not os.path.exists(data_file): + return False + + if md5(data_file) != self.MD5: + return False + data = load(data_file) + for video_pth in data['video_path']: + if not osp.exists(osp.join(pth, video_pth)): + return False + return True + + cache_path = get_cache_path(repo_id) + if cache_path is not None and check_integrity(cache_path): + dataset_path = cache_path + else: + + def unzip_hf_zip(pth): + import zipfile + from moviepy.editor import VideoFileClip + base_dir = pth + target_dir = os.path.join(pth, 'videos/') + zip_files = [ + os.path.join(base_dir, file) for file in os.listdir(base_dir) + if file.endswith('.zip') and file.startswith('worldsense_videos') + ] + zip_files.sort() + + if not os.path.exists(target_dir): + os.makedirs(target_dir, exist_ok=True) + for zip_file in zip_files: + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + for member in zip_ref.namelist(): + # Check if the member is a file (not a directory) + if not member.endswith('/'): + # Extract the file to the specified directory + source = zip_ref.open(member) + target = open(os.path.join(target_dir, os.path.basename(member)), 'wb') + with source, target: + target.write(source.read()) + print('The video file has been restored and stored from the zip file.') + else: + print('The video file already exists.') + + subtitle_zip_file = os.path.join(base_dir, 'worldsense_subtitles.zip') + subtitle_target_dir = os.path.join(base_dir, 'subtitles') + + if not os.path.exists(subtitle_target_dir): + os.makedirs(subtitle_target_dir, exist_ok=True) + with zipfile.ZipFile(subtitle_zip_file, 'r') as zip_ref: + for member in zip_ref.namelist(): + # Check if the member is a file (not a directory) + if not member.endswith('/'): + # Extract the file to the specified directory + source = zip_ref.open(member) + target = open(os.path.join(subtitle_target_dir, os.path.basename(member)), 'wb') + with source, target: + target.write(source.read()) + print('The subtitle file has been restored and stored from the zip file.') + else: + print('The subtitle file already exists.') + + audio_target_dir = os.path.join(base_dir, 'audios') + if not os.path.exists(audio_target_dir): + os.makedirs(audio_target_dir, exist_ok=True) + videos = os.listdir(target_dir) + for video in videos: + video_path = os.path.join(target_dir, video) + audio_path = os.path.join(audio_target_dir, video.replace('.mp4', '.wav')) + video = VideoFileClip(video_path) + audio = video.audio + audio.write_audiofile(audio_path, verbose=False, logger=None) + video.close() + audio.close() + print('The audio file has been extracted from videos.') + else: + print('The audio file already exists.') + + def generate_tsv(pth): + + data_file = osp.join(pth, f'{dataset_name}.tsv') + print(data_file, md5(data_file)) + if os.path.exists(data_file) and md5(data_file) == self.MD5: + return + + with open(osp.join(pth, 'worldsense_qa.json'), 'rb') as file: + json_data = json.load(file) + + videos = list(json_data.keys()) + qa_index = 0 + data_list = [] + data_list.append([ + 'index', 'video', 'video_path', 'duration', 'domain', 'candidates', + 'sub_category', 'audio_class', 'task_domain', 'task_type', 'subtitle_path', + 'audio_path', 'video_caption', 'question', 'answer' + ]) + for video in videos: + video_data = json_data[video] + tasks_data = list(video_data.keys()) + tasks_data = [task for task in tasks_data if 'task' in task] + for _task in tasks_data: + task_list = [] + _task_data = video_data[_task] + task_list.append(qa_index) + task_list.append(str(video)) + task_list.append(f'./videos/{video}.mp4') + task_list.append(video_data['duration']) + task_list.append(video_data['domain']) + task_list.append(_task_data['candidates']) + task_list.append(video_data['sub_category']) + task_list.append(video_data['audio_class']) + task_list.append(_task_data['task_domain']) + task_list.append(_task_data['task_type']) + task_list.append(f'./subtitles/{video}.srt') + task_list.append(f'./audios/{video}.wav') + task_list.append(video_data['video_caption']) + task_list.append(_task_data['question']) + task_list.append(_task_data['answer']) + + data_list.append(task_list) + qa_index += 1 + + data_file = data_list + data_file = pd.DataFrame(data_file[1:], columns=data_file[0]) + + data_file.to_csv(osp.join(pth, f'{dataset_name}.tsv'), sep='\t', index=False) + + if modelscope_flag_set(): + from modelscope import dataset_snapshot_download + dataset_path = dataset_snapshot_download(dataset_id=repo_id) + else: + dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') + unzip_hf_zip(dataset_path) + generate_tsv(dataset_path) + + data_file = osp.join(dataset_path, f'{dataset_name}.tsv') + + return dict(data_file=data_file, root=dataset_path) + + def save_video_frames(self, video, video_llm=False): + + vid_path = osp.join(self.data_root, 'videos', video + '.mp4') + import decord + vid = decord.VideoReader(vid_path) + video_info = { + 'fps': vid.get_avg_fps(), + 'n_frames': len(vid), + } + if self.nframe > 0 and self.fps < 0: + step_size = len(vid) / (self.nframe + 1) + indices = [int(i * step_size) for i in range(1, self.nframe + 1)] + frame_paths = self.frame_paths(video) + elif self.fps > 0: + # not constrained by num_frames, get frames by fps + total_duration = video_info['n_frames'] / video_info['fps'] + required_frames = int(total_duration * self.fps) + step_size = video_info['fps'] / self.fps + indices = [int(i * step_size) for i in range(required_frames)] + frame_paths = self.frame_paths_fps(video, len(indices)) + + flag = np.all([osp.exists(p) for p in frame_paths]) + + if not flag: + lock_path = osp.splitext(vid_path)[0] + '.lock' + with portalocker.Lock(lock_path, 'w', timeout=30): + if not np.all([osp.exists(p) for p in frame_paths]): + images = [vid[i].asnumpy() for i in indices] + images = [Image.fromarray(arr) for arr in images] + for im, pth in zip(images, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths, indices, video_info + + def build_prompt(self, line, video_llm): + if isinstance(line, int): + assert line < len(self) + line = self.data.iloc[line] + + frames, indices, video_info = self.save_video_frames(line['video'], video_llm) + + if self.use_subtitle and os.path.exists(osp.join(self.data_root, line['subtitle_path'])): + import pysubs2 + subs = pysubs2.load(osp.join(self.data_root, line['subtitle_path']), encoding='utf-8') + subtitles = [] + + if video_llm: + n_frame_list = list(range(0, video_info['n_frames'], 1)) + indices = n_frame_list[0:-1:int(video_info['fps'])] + for seleced_frame_id in indices: + sub_text = '' + cur_time = pysubs2.make_time(fps=video_info['fps'], frames=seleced_frame_id) + for sub in subs: + if sub.start < cur_time and sub.end > cur_time: + sub_text = sub.text.replace('\\N', ' ') + break + if sub_text.strip(): + subtitles.append(sub_text) + subtitles = '\n'.join(subtitles) + else: + subtitles = '' + + message = [dict(type='text', value=self.SYS)] + if video_llm: + message.append(dict(type='video', value=osp.join(self.data_root, 'videos', line['video'] + '.mp4'))) + if self.use_audio: + message.append(dict(type='audio', value=osp.join(self.data_root, 'audios', line['video'] + '.wav'))) + else: + for im in frames: + message.append(dict(type='image', value=im)) + if self.use_audio: + message.append(dict(type='audio', value=osp.join(self.data_root, 'audios', line['video'] + '.wav'))) + + if self.use_subtitle: + text_prompt = self.FRAMES_TMPL_SUB.format(subtitles) + elif self.use_audio: + text_prompt = self.FRAMES_TMPL_AUDIO + else: + text_prompt = self.FRAMES_TMPL_NOSUB + message.append(dict(type='text', value=text_prompt)) + question_str = line['question'] + '\n' + '\n'.join(eval(line['candidates'])) + prompt = 'Question: {}\nAnswer: '.format(question_str) + message.append(dict(type='text', value=prompt)) + return message + + # It returns a dictionary + @classmethod + def evaluate(self, eval_file, **judge_kwargs): + from .utils.worldsense import get_dimension_rating, extract_characters_regex, extract_option + + assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 + + tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') + tgt_file = get_intermediate_file_path(eval_file, '_rating', 'json') + score_file = get_intermediate_file_path(eval_file, '_score') + + if not osp.exists(score_file): + model = judge_kwargs.get('model', 'exact_matching') + assert model in ['chatgpt-0125', 'exact_matching', 'gpt-4-0125'] + + if model == 'exact_matching': + model = None + elif gpt_key_set(): + model = build_judge(**judge_kwargs) + if not model.working(): + warnings.warn('OPENAI API is not working properly, will use exact matching for evaluation') + warnings.warn(DEBUG_MESSAGE) + model = None + else: + warnings.warn('OPENAI_API_KEY is not set properly, will use exact matching for evaluation') + model = None + res = {} if not osp.exists(tmp_file) else load(tmp_file) + res = {k: v for k, v in res.items() if FAIL_MSG not in v} + + data = load(eval_file) + data_un = data[~pd.isna(data['prediction'])] + + for idx in data['index']: + ans = data.loc[data['index'] == idx, 'answer'].values[0] + pred = str(data.loc[data['index'] == idx, 'prediction'].values[0]) + + if extract_characters_regex(pred) == '': + extract_pred = extract_option( + model, + data.loc[data['index'] == idx].to_dict(orient='records')[0], + 'WorldSense' + ) + data.loc[idx, 'score'] = int(extract_pred == ans) + else: + data.loc[idx, 'score'] = int(extract_characters_regex(pred) == ans) + + rejected = [x for x in data['score'] if x == -1] + + print( + f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' + f'failed to obtain the score for another {len(rejected)} questions. ' + f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' + ) + + dump(data, score_file) + + rating = get_dimension_rating(score_file) + dump(rating, tgt_file) + return rating diff --git a/VLMEvalKit-sudoku/vlmeval/smp/__init__.py b/VLMEvalKit-sudoku/vlmeval/smp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46e89687d469b83ec7dd7e3205841d35087108c7 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/smp/__init__.py @@ -0,0 +1,4 @@ +from .file import * +from .vlm import * +from .misc import * +from .log import * diff --git a/VLMEvalKit-sudoku/vlmeval/smp/log.py b/VLMEvalKit-sudoku/vlmeval/smp/log.py new file mode 100644 index 0000000000000000000000000000000000000000..8a44b6be6971eabfe5eb15b4b8e428ff01d5086e --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/smp/log.py @@ -0,0 +1,49 @@ +import logging +logging.basicConfig( + format='[%(asctime)s] %(levelname)s - %(filename)s: %(funcName)s - %(lineno)d: %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + +logger_initialized = {} + + +def get_logger(name, log_file=None, log_level=logging.INFO, file_mode='w'): + logger = logging.getLogger(name) + if name in logger_initialized: + return logger + + for logger_name in logger_initialized: + if name.startswith(logger_name): + return logger + + stream_handler = logging.StreamHandler() + handlers = [stream_handler] + + try: + import torch.distributed as dist + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + else: + rank = 0 + except ImportError: + rank = 0 + + if rank == 0 and log_file is not None: + file_handler = logging.FileHandler(log_file, file_mode) + handlers.append(file_handler) + + formatter = logging.Formatter( + '[%(asctime)s] %(levelname)s - %(name)s - %(filename)s: %(funcName)s - %(lineno)d: %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + for handler in handlers: + handler.setFormatter(formatter) + handler.setLevel(log_level) + logger.propagate = False + logger.addHandler(handler) + + if rank == 0: + logger.setLevel(log_level) + else: + logger.setLevel(logging.ERROR) + + logger_initialized[name] = True + return logger diff --git a/VLMEvalKit-sudoku/vlmeval/smp/misc.py b/VLMEvalKit-sudoku/vlmeval/smp/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..85be2cb671e884269853bf04852b888977ac8e14 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/smp/misc.py @@ -0,0 +1,278 @@ +# flake8: noqa: F401, F403 +import abc +import argparse +import csv +import multiprocessing as mp +import os +import os.path as osp +from pathlib import Path +import copy as cp +import random as rd +import requests +import shutil +import subprocess +import warnings +import pandas as pd +from collections import OrderedDict, defaultdict +from multiprocessing import Pool, current_process +from tqdm import tqdm +import datetime +import matplotlib.pyplot as plt +from tabulate import tabulate +from json import JSONDecoder +from huggingface_hub import scan_cache_dir +from huggingface_hub.utils._cache_manager import _scan_cached_repo +from sty import fg, bg, ef, rs +import portalocker + + +def modelscope_flag_set(): + return os.environ.get('VLMEVALKIT_USE_MODELSCOPE', None) in ['1', 'True'] + + +def process_punctuation(inText): + import re + outText = inText + punct = [ + ';', r'/', '[', ']', '"', '{', '}', '(', ')', '=', '+', '\\', '_', '-', + '>', '<', '@', '`', ',', '?', '!' + ] + commaStrip = re.compile(r'(\d)(,)(\d)') + periodStrip = re.compile(r'(? 0: + try: + package_base = package.split('=')[0] + module = __import__(package) + return True + except ImportError: + subprocess.check_call([sys.executable, '-m', 'pip', 'install', package]) + retry -= 1 + return False + + +def version_cmp(v1, v2, op='eq'): + from packaging import version + import operator + op_func = getattr(operator, op) + return op_func(version.parse(v1), version.parse(v2)) + + +def toliststr(s): + if isinstance(s, str) and (s[0] == '[') and (s[-1] == ']'): + return [str(x) for x in eval(s)] + elif isinstance(s, str): + return [s] + elif isinstance(s, list): + return [str(x) for x in s] + raise NotImplementedError + + +def extract_json_objects(text, decoder=JSONDecoder()): + pos = 0 + while True: + match = text.find('{', pos) + if match == -1: break + try: + result, index = decoder.raw_decode(text[match:]) + yield result + pos = match + index + except ValueError: + pos = match + 1 + + +def get_gpu_memory(): + import subprocess + try: + command = "nvidia-smi --query-gpu=memory.free --format=csv" + memory_free_info = subprocess.check_output(command.split()).decode('ascii').split('\n')[:-1][1:] + memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)] + return memory_free_values + except Exception as e: + print(f'{type(e)}: {str(e)}') + return [] diff --git a/VLMEvalKit-sudoku/vlmeval/smp/vlm.py b/VLMEvalKit-sudoku/vlmeval/smp/vlm.py new file mode 100644 index 0000000000000000000000000000000000000000..53e7fc44c90783df9330b09fb21f36538794fefb --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/smp/vlm.py @@ -0,0 +1,198 @@ +import os +import io +import pandas as pd +import numpy as np +import string +from uuid import uuid4 +import os.path as osp +import base64 +from PIL import Image +import sys + +Image.MAX_IMAGE_PIXELS = 1e9 + + +def rescale_img(img, tgt=None): + assert isinstance(tgt, tuple) and -1 in tgt + w, h = img.size + if tgt[0] != -1: + new_w, new_h = tgt[0], int(tgt[0] / w * h) + elif tgt[1] != -1: + new_w, new_h = int(tgt[1] / h * w), tgt[1] + img = img.resize((new_w, new_h)) + return img + + +def concat_images_vlmeval(images, target_size=-1, mode='h', return_image=False): + from .file import md5 + + ims = [Image.open(im) for im in images] + if target_size != -1: + ims = [ + rescale_img(im, (-1, target_size) if mode == 'h' else (target_size, -1)) + for im in ims + ] + + ws, hs = [x.width for x in ims], [x.height for x in ims] + if mode == 'h': + new_w, new_h = sum(ws), max(hs) + dst = Image.new('RGB', (new_w, new_h)) + for i, im in enumerate(ims): + dst.paste(im, (sum(ws[:i]), 0)) + elif mode == 'v': + new_w, new_h = max(ws), sum(hs) + dst = Image.new('RGB', (new_w, new_h)) + for i, im in enumerate(ims): + dst.paste(im, (sum(ws[:i], 0))) + if return_image: + return dst + else: + _str = '\n'.join(images) + str_md5 = md5(_str) + tgt = osp.join('/tmp', str_md5 + '.jpg') + dst.save(tgt) + return tgt + + +def mmqa_display(question, target_size=-1): + question = {k.lower(): v for k, v in question.items()} + keys = list(question.keys()) + keys = [k for k in keys if k not in ['index', 'image']] + + if 'image' in question: + images = question.pop('image') + if images[0] == '[' and images[-1] == ']': + images = eval(images) + else: + images = [images] + else: + images = question.pop('image_path') + if images[0] == '[' and images[-1] == ']': + images = eval(images) + else: + images = [images] + images = [encode_image_file_to_base64(x) for x in images] + + idx = question.pop('index', 'XXX') + print(f'INDEX: {idx}') + + for im in images: + image = decode_base64_to_image(im, target_size=target_size) + display(image) # noqa: F821 + + for k in keys: + try: + if not pd.isna(question[k]): + print(f'{k.upper()}. {question[k]}') + except ValueError: + if False in pd.isna(question[k]): + print(f'{k.upper()}. {question[k]}') + + +def resize_image_by_factor(img, factor=1): + w, h = img.size + new_w, new_h = int(w * factor), int(h * factor) + img = img.resize((new_w, new_h)) + return img + + +def encode_image_to_base64(img, target_size=-1, fmt='JPEG'): + # if target_size == -1, will not do resizing + # else, will set the max_size ot (target_size, target_size) + if img.mode in ('RGBA', 'P', 'LA'): + img = img.convert('RGB') + if target_size > 0: + img.thumbnail((target_size, target_size)) + img_buffer = io.BytesIO() + img.save(img_buffer, format=fmt) + image_data = img_buffer.getvalue() + ret = base64.b64encode(image_data).decode('utf-8') + max_size = os.environ.get('VLMEVAL_MAX_IMAGE_SIZE', 1e9) + min_edge = os.environ.get('VLMEVAL_MIN_IMAGE_EDGE', 1e2) + max_size = int(max_size) + min_edge = int(min_edge) + + if min(img.size) < min_edge: + factor = min_edge / min(img.size) + image_new = resize_image_by_factor(img, factor) + img_buffer = io.BytesIO() + image_new.save(img_buffer, format=fmt) + image_data = img_buffer.getvalue() + ret = base64.b64encode(image_data).decode('utf-8') + + factor = 1 + while len(ret) > max_size: + factor *= 0.7 # Half Pixels Per Resize, approximately + image_new = resize_image_by_factor(img, factor) + img_buffer = io.BytesIO() + image_new.save(img_buffer, format=fmt) + image_data = img_buffer.getvalue() + ret = base64.b64encode(image_data).decode('utf-8') + + if factor < 1: + new_w, new_h = image_new.size + print( + f'Warning: image size is too large and exceeds `VLMEVAL_MAX_IMAGE_SIZE` {max_size}, ' + f'resize to {factor:.2f} of original size: ({new_w}, {new_h})' + ) + + return ret + + +def encode_image_file_to_base64(image_path, target_size=-1, fmt='JPEG'): + image = Image.open(image_path) + return encode_image_to_base64(image, target_size=target_size, fmt=fmt) + + +def decode_base64_to_image(base64_string, target_size=-1): + image_data = base64.b64decode(base64_string) + image = Image.open(io.BytesIO(image_data)) + if image.mode in ('RGBA', 'P', 'LA'): + image = image.convert('RGB') + if target_size > 0: + image.thumbnail((target_size, target_size)) + return image + + +def decode_base64_to_image_file(base64_string, image_path, target_size=-1): + image = decode_base64_to_image(base64_string, target_size=target_size) + base_dir = osp.dirname(image_path) + if not osp.exists(base_dir): + os.makedirs(base_dir, exist_ok=True) + image.save(image_path) + + +def build_option_str(option_dict): + s = 'There are several options: \n' + for c, content in option_dict.items(): + if not pd.isna(content): + s += f'{c}. {content}\n' + return s + + +def isimg(s): + return osp.exists(s) or s.startswith('http') + + +def read_ok(img_path): + if not osp.exists(img_path): + return False + try: + im = Image.open(img_path) + assert im.size[0] > 0 and im.size[1] > 0 + return True + except: + return False + + +def gpt_key_set(): + openai_key = os.environ.get('OPENAI_API_KEY', None) + if openai_key is None: + openai_key = os.environ.get('AZURE_OPENAI_API_KEY', None) + return isinstance(openai_key, str) + return isinstance(openai_key, str) and openai_key.startswith('sk-') + + +def apiok(wrapper): + s = wrapper.generate('Hello!') + return wrapper.fail_msg not in s diff --git a/VLMEvalKit-sudoku/vlmeval/utils/__init__.py b/VLMEvalKit-sudoku/vlmeval/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cabf84344917f1e41310d3f20a8df269e92d3b27 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/utils/__init__.py @@ -0,0 +1,7 @@ +from .matching_util import can_infer, can_infer_option, can_infer_text, can_infer_sequence, can_infer_lego +from .mp_util import track_progress_rich + + +__all__ = [ + 'can_infer', 'can_infer_option', 'can_infer_text', 'track_progress_rich', 'can_infer_sequence', 'can_infer_lego', +] diff --git a/VLMEvalKit-sudoku/vlmeval/utils/matching_util.py b/VLMEvalKit-sudoku/vlmeval/utils/matching_util.py new file mode 100644 index 0000000000000000000000000000000000000000..325835f811fa07cfda46be0a47451b782c7f7428 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/utils/matching_util.py @@ -0,0 +1,126 @@ +import string +import copy as cp +import os +from ..smp import * +import re + + +def can_infer_option(answer, choices): + verbose = os.environ.get('VERBOSE', 0) + # Choices is a dictionary + if 'Failed to obtain answer via API' in answer: + return False + + reject_to_answer = [ + "Sorry, I can't help with images of people yet.", + "I can't process this file.", + "I'm sorry, but without the image provided", + 'Cannot determine the answer' + ] + for err in reject_to_answer: + if err in answer: + return 'Z' + + def count_choice(splits, choices, prefix='', suffix=''): + cnt = 0 + for c in choices: + if prefix + c + suffix in splits: + cnt += 1 + return cnt + + answer_mod = cp.copy(answer) + chars = '.()[],:;!*#{}' + for c in chars: + answer_mod = answer_mod.replace(c, ' ') + + splits = [x.strip() for x in answer_mod.split()] + count = count_choice(splits, choices) + + if count == 1: + for ch in choices: + if 'A' in splits and len(splits) > 3 and verbose: + logger = get_logger('Evaluation') + logger.info(f'A might be a quantifier in the string: {answer}.') + return False + if ch in splits and splits.index(ch) > (len(splits) - 5): + return ch + elif count == 0 and count_choice(splits, {'Z', ''}) == 1: + return 'Z' + return False + + +def can_infer_sequence(answer, choices=None): + answer_upper = answer.upper() + + sequence_match = re.search(r'\b([A-D]{4})\b', answer_upper) + if sequence_match: + candidate = sequence_match.group(1) + if len(set(candidate)) == 4: + return candidate + + order_patterns = [ + r'(?:first|1st|首先|第一步).*?([A-D])', + r'(?:second|2nd|其次|第二步).*?([A-D])', + r'(?:third|3rd|再次|第三步).*?([A-D])', + r'(?:fourth|4th|最后|第四步).*?([A-D])' + ] + + sequence = [] + for pattern in order_patterns: + match = re.search(pattern, answer_upper, re.IGNORECASE) + if match: + option = match.group(1).upper() + if option not in sequence: + sequence.append(option) + + if len(sequence) == 4: + return ''.join(sequence) + + step_pattern = ( + r'(?:step\s*[\d一二三四]+|' + r'步骤\s*[\d一二三四]+|' + r'第\s*[\d一二三四]\s*步)' + r'.*?([A-D])' + ) + step_matches = re.findall(step_pattern, answer_upper, re.IGNORECASE) + if len(step_matches) >= 4: + unique = [] + for m in step_matches[:4]: + if m.upper() not in unique: + unique.append(m.upper()) + if len(unique) == 4: + return ''.join(unique) + + return False + + +def can_infer_text(answer, choices): + answer = answer.lower() + if len(answer) > 2 * sum(len(str(v)) for v in choices.values()): + return False + assert isinstance(choices, dict) + for k in choices: + assert k in string.ascii_uppercase + choices[k] = str(choices[k]).lower() + cands = [] + for k in choices: + if choices[k] in answer: + cands.append(k) + if len(cands) == 1: + return cands[0] + return False + + +def can_infer(answer, choices): + answer = str(answer) + copt = can_infer_option(answer, choices) + return copt if copt else can_infer_text(answer, choices) + + +def can_infer_lego(answer, question_type, choices): + answer = str(answer) + if question_type == 'sort': + copt = can_infer_sequence(answer, choices) + else: # multiple-choice + copt = can_infer_option(answer, choices) # option + return copt if copt else can_infer_text(answer, choices) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/deepseek_vl.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/deepseek_vl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d285c813c077a48296d59bba287fd4d122b33f34 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/deepseek_vl.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/long_vita.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/long_vita.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91a492078e7b7558d369118e7eba71c071da8629 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/long_vita.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/minicpm_v.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/minicpm_v.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a815c6d97959ed3c99b00f94b7e72960a3a3e8f2 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/minicpm_v.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/mixsense.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/mixsense.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..253eae596d42d6c3a67f2543b1279c4283fd2109 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/mixsense.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/varco_vision.cpython-310.pyc b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/varco_vision.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90db57737831159b66ddc98aa16e0e8a5fded0e3 Binary files /dev/null and b/VLMEvalKit-sudoku/vlmeval/vlm/__pycache__/varco_vision.cpython-310.pyc differ diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/base.py b/VLMEvalKit-sudoku/vlmeval/vlm/base.py new file mode 100644 index 0000000000000000000000000000000000000000..bb1ab95cf478cf5d722448f4b000c0811c6503ce --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/base.py @@ -0,0 +1,221 @@ +from ..smp import * +from ..dataset import img_root_map, DATASET_TYPE +from abc import abstractmethod + + +class BaseModel: + + INTERLEAVE = False + allowed_types = ['text', 'image', 'video'] + + def __init__(self): + self.dump_image_func = None + + def use_custom_prompt(self, dataset): + """Whether to use custom prompt for the given dataset. + + Args: + dataset (str): The name of the dataset. + + Returns: + bool: Whether to use custom prompt. If True, will call `build_prompt` of the VLM to build the prompt. + Default to False. + """ + return False + + @abstractmethod + def build_prompt(self, line, dataset): + """Build custom prompts for a specific dataset. Called only if `use_custom_prompt` returns True. + + Args: + line (line of pd.DataFrame): The raw input line. + dataset (str): The name of the dataset. + + Returns: + str: The built message. + """ + raise NotImplementedError + + def set_dump_image(self, dump_image_func): + self.dump_image_func = dump_image_func + + def dump_image(self, line, dataset): + return self.dump_image_func(line) + + @abstractmethod + def generate_inner(self, message, dataset=None): + raise NotImplementedError + + def check_content(self, msgs): + """Check the content type of the input. Four types are allowed: str, dict, liststr, listdict. + """ + if isinstance(msgs, str): + return 'str' + if isinstance(msgs, dict): + return 'dict' + if isinstance(msgs, list): + types = [self.check_content(m) for m in msgs] + if all(t == 'str' for t in types): + return 'liststr' + if all(t == 'dict' for t in types): + return 'listdict' + return 'unknown' + + def preproc_content(self, inputs): + """Convert the raw input messages to a list of dicts. + + Args: + inputs: raw input messages. + + Returns: + list(dict): The preprocessed input messages. Will return None if failed to preprocess the input. + """ + + if self.check_content(inputs) == 'str': + return [dict(type='text', value=inputs)] + elif self.check_content(inputs) == 'dict': + assert 'type' in inputs and 'value' in inputs + return [inputs] + elif self.check_content(inputs) == 'liststr': + res = [] + for s in inputs: + mime, pth = parse_file(s) + if mime is None or mime == 'unknown': + res.append(dict(type='text', value=s)) + else: + res.append(dict(type=mime.split('/')[0], value=pth)) + return res + elif self.check_content(inputs) == 'listdict': + for item in inputs: + assert 'type' in item and 'value' in item + mime, s = parse_file(item['value']) + if mime is None: + assert item['type'] == 'text' + else: + assert mime.split('/')[0] == item['type'] + item['value'] = s + return inputs + else: + return None + + def generate(self, message, dataset=None): + """Generate the output message. + + Args: + message (list[dict]): The input message. + dataset (str, optional): The name of the dataset. Defaults to None. + + Returns: + str: The generated message. + """ + assert self.check_content(message) in ['str', 'dict', 'liststr', 'listdict'], f'Invalid input type: {message}' + message = self.preproc_content(message) + assert message is not None and self.check_content(message) == 'listdict' + for item in message: + assert item['type'] in self.allowed_types, f'Invalid input type: {item["type"]}' + return self.generate_inner(message, dataset) + + def chat(self, messages, dataset=None): + """The main function for multi-turn chatting. Will call `chat_inner` with the preprocessed input messages.""" + assert hasattr(self, 'chat_inner'), 'The API model should has the `chat_inner` method. ' + for msg in messages: + assert isinstance(msg, dict) and 'role' in msg and 'content' in msg, msg + assert self.check_content(msg['content']) in ['str', 'dict', 'liststr', 'listdict'], msg + msg['content'] = self.preproc_content(msg['content']) + + while len(messages): + try: + return self.chat_inner(messages, dataset=dataset) + except Exception as e: + logging.info(f'{type(e)}: {e}') + messages = messages[1:] + while len(messages) and messages[0]['role'] != 'user': + messages = messages[1:] + continue + return 'Chat Mode: Failed with all possible conversation turns.' + + def message_to_promptimg(self, message, dataset=None): + assert not self.INTERLEAVE + model_name = self.__class__.__name__ + warnings.warn( + f'Model {model_name} does not support interleaved input. ' + 'Will use the first image and aggregated texts as prompt. ') + num_images = len([x for x in message if x['type'] == 'image']) + if num_images == 0: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + image = None + else: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + images = [x['value'] for x in message if x['type'] == 'image'] + if 'BLINK' == dataset: + image = concat_images_vlmeval(images, target_size=512) + else: + image = images[0] + return prompt, image + + def message_to_promptvideo(self, message): + if self.VIDEO_LLM: + num_videos = len([x for x in message if x['type'] == 'video']) + if num_videos == 0: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + video = None + else: + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + video = [x['value'] for x in message if x['type'] == 'video'][0] + return prompt, video + else: + logging.critical('Model does not support video input.') + raise NotImplementedError + + def message_to_promptvideo_withrole(self, message, dataset=None): + if self.VIDEO_LLM: + system, user, assistant, video_list = '', '', '', [] + for msg in message: + if msg['type'] == 'text': + if 'role' in msg and msg['role'] == 'system': + system += msg['value'] + elif 'role' in msg and msg['role'] == 'assistant': + assistant += msg['value'] + else: + user += msg['value'] + elif msg['type'] == 'video': + video_list.append(msg['value']) + question = { + 'system': system, + 'user': user, + 'assistant': assistant + } + if assistant == '': + if listinstr(['MCQ'], DATASET_TYPE(dataset)): + question['assistant'] = 'Best Option: (' + else: + del question['assistant'] + if len(video_list) > 1: + print('VLMEvalKit only support single video as input, take first video as input') + video = video_list[0] + return question, video + else: + logging.critical('Model does not support video input.') + raise NotImplementedError + + def message_to_lmdeploy(self, messages, system_prompt=None): + from lmdeploy.vl.constants import IMAGE_TOKEN + from PIL import Image + prompt, image_path = '', [] + for msg in messages: + if msg['type'] == 'text': + prompt += msg['value'] + elif msg['type'] == 'image': + prompt += IMAGE_TOKEN + image_path.append(msg['value']) + content = [{'type': 'text', 'text': prompt}] + for image in image_path: + img = Image.open(image).convert('RGB') + b64 = encode_image_to_base64(img) + img_struct = dict(url=f'data:image/jpeg;base64,{b64}') + content.append(dict(type='image_url', image_url=img_struct)) + ret = [] + if system_prompt is not None: + ret.append(dict(role='system', content=system_prompt)) + ret.append(dict(role='user', content=content)) + return [ret] diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/flash_vl.py b/VLMEvalKit-sudoku/vlmeval/vlm/flash_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..32185752472473671b522b27a8b1475eee290eb2 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/flash_vl.py @@ -0,0 +1,141 @@ +import pandas as pd +import torch +import string +from PIL import Image +from .base import BaseModel +from ..dataset import DATASET_TYPE +from ..smp import listinstr, cn_string +from transformers import AutoModel, AutoTokenizer, CLIPImageProcessor + + +class FlashVL(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path, **kwargs): + assert model_path is not None + self.model_path = model_path + self.model = AutoModel.from_pretrained(model_path, + torch_dtype=torch.bfloat16, + trust_remote_code=True, + device_map='cuda') + self.model.tokenizer = AutoTokenizer.from_pretrained(model_path, + device_map='cuda') + self.model.im_trans = CLIPImageProcessor.from_pretrained( + model_path, trust_remote_code=True) + self.INTERLEAVE = False + + def build_history(self, message): + + def concat_tilist(tilist): + image_cnt = 1 + prompt = '' + for item in tilist: + if item['type'] == 'text': + prompt += item['value'] + elif item['type'] == 'image': + prompt += f"Picture {image_cnt}: {item['value']}\n" + image_cnt += 1 + return prompt + + assert len(message) % 2 == 0 + hist = [] + for i in range(len(message) // 2): + m1, m2 = message[2 * i], message[2 * i + 1] + assert m1['role'] == 'user' and m2['role'] == 'assistant' + hist.append( + (concat_tilist(m1['content']), concat_tilist(m2['content']))) + return hist + + def generate_inner(self, message, dataset=None): + text, img_path = self.message_to_promptimg(message, dataset=dataset) + pil_image = Image.open(img_path).convert('RGB') + messages = [{'role': 'user', 'content': text}] + answer = self.model.chat(pil_image, + messages, + do_sample=False, + max_new_tokens=512) + return answer + + def chat_inner(self, message, dataset=None): + assert len(message) % 2 == 1 and message[-1]['role'] == 'user' + history = self.build_history(message[:-1]) + vl_list = [{ + 'image': s['value'] + } if s['type'] == 'image' else { + 'text': s['value'] + } for s in message[-1]['content']] + query = self.tokenizer.from_list_format(vl_list) + response, _ = self.model.chat(self.tokenizer, + query=query, + history=history, + **self.kwargs) + return response + + def use_custom_prompt(self, dataset): + + if dataset is not None and listinstr(['MMDU'], dataset): + # For Multi-Turn we don't have custom prompt + return False + else: + return True + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + + if dataset is not None and listinstr(['MME'], dataset): + question = line['question'] + prompt = question + ' Answer the question using a single word or phrase.' + elif dataset is not None and listinstr(['HallusionBench'], dataset): + question = line['question'] + prompt = question + ' Please answer yes or no. Answer the question using a single word or phrase.' + elif dataset is not None and DATASET_TYPE(dataset) == 'MCQ': + prompt = self.build_multi_choice_prompt(line, dataset) + elif dataset is not None and DATASET_TYPE(dataset) == 'VQA': + if listinstr(['MathVista', 'MathVision'], dataset): + prompt = line['question'] + elif listinstr(['LLaVABench'], dataset): + question = line['question'] + prompt = question + '\nAnswer this question in detail.' + elif listinstr(['MMVet', 'OCRBench'], dataset): + prompt = line[ + 'question'] + ' Anylyze the reason for the answer.' + elif listinstr(['MTBench_VQA'], dataset): + prompt = line['question'] + '\n 请直接回答问题' + else: + question = line['question'] + prompt = question + '\nAnswer the question using a single word or phrase.' + else: + prompt = line['question'] + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def build_multi_choice_prompt(self, line, dataset=None): + question = line['question'] + hint = line['hint'] if ('hint' in line + and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + prompt += '\n请直接回答选项字母。' if cn_string( + prompt + ) else "\nAnswer with the option's letter from the given choices directly." + else: + prompt += '\n请直接回答问题。' if cn_string( + prompt) else '\nAnswer the question directly.' + + return prompt diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/gemma.py b/VLMEvalKit-sudoku/vlmeval/vlm/gemma.py new file mode 100644 index 0000000000000000000000000000000000000000..bdfee27a473e801fa637a16107380094529bbbdd --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/gemma.py @@ -0,0 +1,230 @@ +from PIL import Image +import torch + +from .base import BaseModel +from ..smp import * + +from io import BytesIO +import base64 +from mimetypes import guess_type + + +class PaliGemma(BaseModel): + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='google/paligemma-3b-mix-448', **kwargs): + try: + from transformers import AutoProcessor, PaliGemmaForConditionalGeneration + except Exception as e: + logging.critical('Please install the latest version transformers.') + raise e + + model = PaliGemmaForConditionalGeneration.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + device_map='cpu', + revision='bfloat16', + ).eval() + self.model = model.cuda() + self.processor = AutoProcessor.from_pretrained(model_path) + self.kwargs = kwargs + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + image = Image.open(image_path).convert('RGB') + + model_inputs = self.processor( + text=prompt, images=image, return_tensors='pt' + ).to('cuda') + input_len = model_inputs['input_ids'].shape[-1] + + with torch.inference_mode(): + generation = self.model.generate( + **model_inputs, max_new_tokens=512, do_sample=False + ) + generation = generation[0][input_len:] + res = self.processor.decode(generation, skip_special_tokens=True) + return res + + +class Gemma3(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='google/gemma-3-4b-it', **kwargs): + logging.info( + "Please install transformers via \n" + "pip install git+https://github.com/huggingface/transformers@v4.49.0-Gemma-3" + ) + try: + from transformers import AutoProcessor, Gemma3ForConditionalGeneration + import torch + except Exception as e: + logging.critical('Please install torch and transformers') + raise e + + self.use_vllm = kwargs.get('use_vllm', False) + self.limit_mm_per_prompt = 24 + if self.use_vllm: + from vllm import LLM, SamplingParams + # Set tensor_parallel_size [8, 4, 2, 1] based on the number of available GPUs + gpu_count = torch.cuda.device_count() + if gpu_count >= 8: + tp_size = 8 + elif gpu_count >= 4: + tp_size = 4 + elif gpu_count >= 2: + tp_size = 2 + else: + tp_size = 1 + logging.info( + f'Using vLLM for Llama4 inference with {tp_size} GPUs (available: {gpu_count})' + ) + import os + if os.environ.get('VLLM_WORKER_MULTIPROC_METHOD') != 'spawn': + logging.warning( + 'VLLM_WORKER_MULTIPROC_METHOD is not set to spawn.' + 'Use \'export VLLM_WORKER_MULTIPROC_METHOD=spawn\' to avoid potential multi-process issues' + ) + self.llm = LLM( + model=model_path, + max_num_seqs=4, + max_model_len=16384, + limit_mm_per_prompt={"image": self.limit_mm_per_prompt}, + tensor_parallel_size=tp_size, + gpu_memory_utilization=kwargs.get("gpu_utils", 0.9), + ) + # export VLLM_WORKER_MULTIPROC_METHOD=spawn + else: + self.model = Gemma3ForConditionalGeneration.from_pretrained( + model_path, device_map="cuda", attn_implementation="flash_attention_2", torch_dtype=torch.bfloat16 + ).eval() + self.device = self.model.device + + self.processor = AutoProcessor.from_pretrained(model_path) + self.system_prompt = kwargs.pop('system_prompt', 'You are a helpful assistant. ') + default_kwargs = { + 'do_sample': False, + 'max_new_tokens': 4096 + } + default_kwargs.update(kwargs) + self.kwargs = default_kwargs + + def message2pipeline(self, message): + ret = [] + if hasattr(self, 'system_prompt') and self.system_prompt is not None: + ret = [ + dict(role='system', content=[dict(type='text', text=self.system_prompt)]) + ] + content = [] + for m in message: + if m['type'] == 'text': + content.append(dict(type='text', text=m['value'])) + elif m['type'] == 'image': + content.append(dict(type='image', url=m['value'])) + ret.append(dict(role='user', content=content)) + return ret + + def encode_image(self, image_path): + mime_type, _ = guess_type(image_path) + if mime_type is None: + mime_type = "image/jpeg" + image_format = mime_type.split("/")[-1].upper() if mime_type else "JPEG" + image = Image.open(image_path) + # Handle the alpha channel + if image.mode == "RGBA": + image = self._rgba_to_rgb(image) + + encoded_image = self._encode_image(image, image_format) + + return encoded_image + + def _encode_image(self, image, image_format): + with BytesIO() as output: + image.convert("RGB").save(output, format=image_format) + base64_encoded_data = base64.b64encode(output.getvalue()).decode("utf-8") + return base64_encoded_data + + @staticmethod + def _rgba_to_rgb(image): + background = Image.new("RGBA", image.size, (255, 255, 255, 255)) + return Image.alpha_composite(background, image).convert("RGB") + + def message_to_promptimg_vllm(self, message, dataset=None): + processed_message = [] + images = [] + num_images = 0 + for item in message: + if item['type'] == 'text': + processed_message.append({ + "type": "text", + "text": item['value'] + }) + elif item['type'] == 'image': + if num_images < self.limit_mm_per_prompt: + image_path = item['value'] + encoded_image = self.encode_image(image_path) + image = Image.open(BytesIO(base64.b64decode(encoded_image))) + image.load() + processed_message.append({ + "type": "image", + "image": "", + }) + images.append(image) + num_images += 1 + if num_images >= self.limit_mm_per_prompt: + logging.warning( + f"Number of images exceeds the limit of {self.limit_mm_per_prompt}." + f"Only the first {self.limit_mm_per_prompt} images will be used." + ) + return processed_message, images + + def generate_inner_transformers(self, message, dataset=None): + messages = self.message2pipeline(message) + inputs = self.processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=True, + return_dict=True, return_tensors="pt", + ).to(self.device, dtype=torch.bfloat16) + + input_len = inputs['input_ids'].shape[-1] + + with torch.inference_mode(): + generation = self.model.generate(**inputs, **self.kwargs) + generation = generation[0][input_len:] + + decoded = self.processor.decode(generation, skip_special_tokens=True) + return decoded + + def generate_inner_vllm(self, message, dataset=None): + from vllm import LLM, SamplingParams + prompt, images = self.message_to_promptimg_vllm(message, dataset=dataset) + messages = [ + {'role': 'user', 'content': prompt} + ] + prompt = self.processor.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True + ) + sampling_params = SamplingParams(temperature=0.0, + max_tokens=self.kwargs['max_new_tokens']) + outputs = self.llm.generate( + { + "prompt": prompt, + "multi_modal_data": { + "image": images + }, + }, + sampling_params=sampling_params + ) + for o in outputs: + generated_text = o.outputs[0].text + return generated_text + + def generate_inner(self, message, dataset=None): + if self.use_vllm: + return self.generate_inner_vllm(message, dataset=dataset) + else: + return self.generate_inner_transformers(message, dataset=dataset) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/idefics.py b/VLMEvalKit-sudoku/vlmeval/vlm/idefics.py new file mode 100644 index 0000000000000000000000000000000000000000..b95c0ef47ce48cc46cb25479381945d03c431445 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/idefics.py @@ -0,0 +1,309 @@ +import torch +import os.path as osp +import warnings +from .base import BaseModel +from ..smp import splitlen, listinstr +from PIL import Image +from transformers.image_utils import load_image + + +class IDEFICS(BaseModel): + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='HuggingFaceM4/idefics-9b-instruct', **kwargs): + assert osp.exists(model_path) or splitlen(model_path) == 2 + from transformers import IdeficsForVisionText2Text, AutoProcessor + + self.model = IdeficsForVisionText2Text.from_pretrained( + model_path, torch_dtype=torch.bfloat16, device_map="auto" + ) + self.processor = AutoProcessor.from_pretrained(model_path) + kwargs_default = {'max_new_tokens': 512} + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + self.file_root = osp.dirname(__file__) + warnings.warn( + f'Following kwargs received: {self.kwargs}, will use as generation config. ' + ) + + def generate_inner(self, message, dataset=None): + prompts = ( + ['Users:'] + + [msg['value'] if msg['type'] == 'text' else Image.open(msg['value']) for msg in message] + + ['', '\nAssistant: '] + ) + inputs = self.processor( + prompts, add_end_of_utterance_token=False, return_tensors='pt' + ).to('cuda') + exit_condition = self.processor.tokenizer( + '', add_special_tokens=False + ).input_ids + bad_words_ids = self.processor.tokenizer( + ['', ''], add_special_tokens=False + ).input_ids + + generated_ids = self.model.generate( + **inputs, + eos_token_id=exit_condition, + bad_words_ids=bad_words_ids, + **self.kwargs, + ) + generated_text = self.processor.batch_decode( + generated_ids, skip_special_tokens=True + ) + text = generated_text[0].split('\nAssistant: ')[-1] + return text + + +class IDEFICS2(BaseModel): + INSTALL_REQ = True + INTERLEAVE = True + + def __init__(self, model_path='HuggingFaceM4/idefics2-8b', **kwargs): + from transformers import AutoProcessor, AutoModelForVision2Seq + assert model_path is not None + self.model_path = model_path + if 'Idefics3' in self.model_path.lower(): + warnings.warn('Install transfomers from source: PR https://github.com/open-compass/VLMEvalKit/pull/379') + warnings.warn('Reference: https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3') + self.processor = AutoProcessor.from_pretrained(model_path) + model = AutoModelForVision2Seq.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + _attn_implementation="flash_attention_2", + device_map="auto") + self.model = model + + kwargs_default = {'max_new_tokens': 1024} + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + warnings.warn( + f'Following kwargs received: {self.kwargs}, will use as generation config. ' + ) + torch.cuda.empty_cache() + + def _process(self, formatted_messages, formatted_images): + inputs = self.processor( + text=formatted_messages, images=formatted_images, return_tensors='pt' + ) + inputs = {k: v.to(self.model.device) for k, v in inputs.items()} + return inputs + + def build_prompt_default(self, message, add_brief=False, add_yes_or_no=False, change_the_img_place=False): + if change_the_img_place: + new_message = [] + for s in message: + if s['type'] == 'image': + new_message.append(s) + for s in message: + if s['type'] == 'text': + new_message.append(s) + message = new_message + prompt, images = 'User:', [] + for msg in message: + if msg['type'] == 'image': + img = load_image(msg['value']) + images.append(img) + prompt += '' + elif msg['type'] == 'text': + prompt += msg['value'].strip() + if add_brief: + prompt += '\nGive a very brief answer.' + if add_yes_or_no: + prompt += '\nAnswer yes or no.' + prompt += '\nAssistant:' + return prompt, images + + def build_prompt_puremcq(self, message): + replace_mapping = { + '\nOptions:': '\nChoices:', + 'Please select the correct answer from the options above.': 'Answer with the letter.', + } + + prompt, images = 'User:', [] + for msg in message: + if msg['type'] == 'image': + img = load_image(msg['value']) + images.append(img) + prompt += '' + elif msg['type'] == 'text': + instruction = msg['value'].strip() + for k, v in replace_mapping.items(): + instruction = instruction.replace(k, v) + prompt += instruction + prompt += '\nAssistant: Answer:' + return prompt, images + + def build_prompt_mt(self, message): + prompt, images = '', [] + for msg in message: + if msg['role'] == 'user': + prompt += 'User: ' + elif msg['role'] == 'assistant': + prompt += 'Assistant: ' + for item in msg['content']: + if item['type'] == 'image': + img = load_image(item['value']) + images.append(img) + prompt += '' + elif item['type'] == 'text': + prompt += item['value'].strip() + prompt += '\n' + return prompt + 'Assistant: ' + + def build_prompt_mmbench(self, message): + replace_mapping = { + '\nOptions:': '\nChoices:', + 'Please select the correct answer from the options above.': 'Answer with a letter.', + } + + prompt, images = 'User:', [] + for msg in message: + if msg['type'] == 'image': + img = load_image(msg['value']) + images.append(img) + prompt += '' + elif msg['type'] == 'text': + instruction = msg['value'].strip() + for k, v in replace_mapping.items(): + instruction = instruction.replace(k, v) + # Swap hint and question + if instruction.startswith('Hint:'): + hint, question = instruction.split('\nQuestion:') + question, choices = question.split('\nChoices:') + instruction = ( + 'Question:' + question + '\n' + hint + '\nChoices:' + choices + ) + prompt += instruction + prompt += '\nAssistant: Answer:' + return prompt, images + + def build_prompt_mmmu(self, message): + replace_mapping = { + 'Question:': '', + 'Please select the correct answer from the options above.': 'Answer with the letter.', + '\nOptions:': '\nChoices:', + } + + prompt, images, img_counter = 'User: Question: ', [], 1 + for msg in message: + if msg['type'] == 'image': + prompt += f':\n' + img_counter += 1 + img_counter = 1 + + for msg in message: + if msg['type'] == 'image': + img = load_image(msg['value']) + images.append(img) + prompt += f' ' + img_counter += 1 + elif msg['type'] == 'text': + instruction = msg['value'].strip() + for k, v in replace_mapping.items(): + instruction = instruction.replace(k, v) + prompt += instruction.strip() + prompt += '\nAssistant:' + if 'A.' in prompt and 'B.' in prompt: + prompt += ' Answer:' + return prompt, images + + def build_prompt_mathvista(self, message): + replace_mapping = { + '(A) ': 'A. ', + '(B) ': 'B. ', + '(C) ': 'C. ', + '(D) ': 'D. ', + '(E) ': 'E. ', + '(F) ': 'F. ', + '(G) ': 'G. ', + '(H) ': 'H. ', + '\nOptions:': '\nChoices:', + 'Hint: ': '', + } + + prompt, images = 'User:', [] + for msg in message: + if msg['type'] == 'image': + img = load_image(msg['value']) + images.append(img) + prompt += '' + elif msg['type'] == 'text': + instruction = msg['value'].strip() + for k, v in replace_mapping.items(): + instruction = instruction.replace(k, v) + prompt += instruction.strip() + if 'A.' in prompt and 'B.' in prompt: + prompt += '\nAnswer with the letter.' + prompt += '\nAssistant:' + if 'A.' in prompt and 'B.' in prompt: + prompt += ' Answer:' + return prompt, images + + def chat_inner(self, message, dataset=None): + formatted_messages, formatted_images = self.build_prompt_mt(message) + inputs = self._process(formatted_messages, formatted_images) + + generated_ids = self.model.generate(**inputs, **self.kwargs) + generated_text = self.processor.batch_decode( + generated_ids[:, inputs['input_ids'].size(1):], skip_special_tokens=True + )[0] + response = generated_text.strip() + # print(dataset, " | ", formatted_messages.replace("\n", "\\n"), " | ", response.replace("\n", "\\n")) + return response + + def generate_inner(self, message, dataset=None): + if dataset in [ + 'MMBench_DEV_EN', 'MMBench_DEV_EN_V11', + 'MMBench_TEST_EN', 'MMBench_TEST_EN_V11', + 'MMBench_DEV_CN', 'MMBench_DEV_CN_V11', + 'MMBench_TEST_CN', 'MMBench_TEST_CN_V11', + 'MMBench', 'MMBench_V11', 'MMBench_CN', 'MMBench_CN_V11' + ]: + formatted_messages, formatted_images = self.build_prompt_mmbench(message) + elif dataset in ['MMMU_DEV_VAL', 'MMMU_TEST']: + formatted_messages, formatted_images = self.build_prompt_mmmu(message) + elif dataset in ['MathVista_MINI']: + formatted_messages, formatted_images = self.build_prompt_mathvista(message) + elif dataset in [ + 'MME', + 'MMVet', + 'OCRVQA_TEST', + 'OCRVQA_TESTCORE', + 'TextVQA_VAL', + 'ChartQA_TEST', + 'DocVQA_VAL', + 'DocVQA_TEST', + 'InfoVQA_VAL', + 'InfoVQA_TEST', + ]: + formatted_messages, formatted_images = self.build_prompt_default( + message, add_brief=True + ) + elif dataset == 'HallusionBench': + formatted_messages, formatted_images = self.build_prompt_default( + message, add_yes_or_no=True + ) + elif dataset in [ + 'MMStar', + 'SEEDBench_IMG', + 'AI2D_TEST', + 'ScienceQA_VAL', + 'ScienceQA_TEST', + ]: + formatted_messages, formatted_images = self.build_prompt_puremcq(message) + elif dataset is not None and listinstr(['MLVU','TempCompass','MVBench'], dataset): + formatted_messages, formatted_images = self.build_prompt_default(message, change_the_img_place=True) + else: + formatted_messages, formatted_images = self.build_prompt_default(message) + + inputs = self._process(formatted_messages, formatted_images) + + generated_ids = self.model.generate(**inputs, **self.kwargs) + generated_text = self.processor.batch_decode( + generated_ids[:, inputs['input_ids'].size(1):], skip_special_tokens=True + )[0] + response = generated_text.strip() + # print(dataset, " | ", formatted_messages.replace("\n", "\\n"), " | ", response.replace("\n", "\\n")) + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/instructblip.py b/VLMEvalKit-sudoku/vlmeval/vlm/instructblip.py new file mode 100644 index 0000000000000000000000000000000000000000..881e60224cc0d5fe199039dfff47e12401b4866a --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/instructblip.py @@ -0,0 +1,57 @@ +import torch +from PIL import Image +import os.path as osp +import sys +from .base import BaseModel +from ..smp import * + + +class InstructBLIP(BaseModel): + + INSTALL_REQ = True + INTERLEAVE = False + + def __init__(self, name): + self.config_map = { + 'instructblip_7b': 'misc/blip2_instruct_vicuna7b.yaml', + 'instructblip_13b': 'misc/blip2_instruct_vicuna13b.yaml', + } + + self.file_path = __file__ + config_root = osp.dirname(self.file_path) + + try: + from lavis.models import load_preprocess + from omegaconf import OmegaConf + from lavis.common.registry import registry + except Exception as e: + logging.critical('Please install lavis before using InstructBLIP. ') + raise e + + assert name in self.config_map + cfg_path = osp.join(config_root, self.config_map[name]) + cfg = OmegaConf.load(cfg_path) + + model_cfg = cfg.model + assert osp.exists(model_cfg.llm_model) or splitlen(model_cfg.llm_model) == 2 + model_cls = registry.get_model_class(name='blip2_vicuna_instruct') + model = model_cls.from_config(model_cfg) + model.eval() + + self.device = torch.device('cuda') if torch.cuda.is_available() else 'cpu' + device = self.device + model.to(device) + self.model = model + self.kwargs = {'max_length': 512} + + preprocess_cfg = cfg.preprocess + vis_processors, _ = load_preprocess(preprocess_cfg) + self.vis_processors = vis_processors + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + vis_processors = self.vis_processors + raw_image = Image.open(image_path).convert('RGB') + image_tensor = vis_processors['eval'](raw_image).unsqueeze(0).to(self.device) + outputs = self.model.generate(dict(image=image_tensor, prompt=prompt)) + return outputs[0] diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/kimi_vl.py b/VLMEvalKit-sudoku/vlmeval/vlm/kimi_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..c926e6f259f01892bf00d07d70deabf0c8839eb3 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/kimi_vl.py @@ -0,0 +1,147 @@ +import re +import numpy as np +from PIL import Image +from transformers import AutoModelForCausalLM, AutoProcessor +from io import BytesIO +import base64 +from mimetypes import guess_type + +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE, DATASET_MODALITY + + +def extract_boxed_content(ans: str): + idx = ans.rfind(r'\boxed{') + if idx == -1: + return ans + + idx += len(r'\boxed{') + brace_level = 1 + content_start = idx + i = idx + + while i < len(ans): + if ans[i] == '{': + brace_level += 1 + elif ans[i] == '}': + brace_level -= 1 + if brace_level == 0: + break + i += 1 + + if brace_level != 0: + # Unbalanced braces + return ans + + content = ans[content_start:i] + return content + + +def extract_summary(text: str, bot: str = "◁think▷", eot: str = "◁/think▷") -> str: + if bot in text and eot not in text: + return "" + if eot in text: + return text[text.index(eot) + len(eot):].strip() + return text + + +class KimiVL(BaseModel): + INSTALL_REQ = False + INTERLEAVE = True + + def __init__( + self, model_path="moonshotai/Kimi-VL-A3B-Thinking", + temperature=0.0, max_tokens=4096, extract_summary=False, **kwargs): + assert model_path is not None + self.model_path = model_path + print(f'load from {self.model_path}') + self.model = AutoModelForCausalLM.from_pretrained( + model_path, + torch_dtype="auto", + device_map="cuda", + trust_remote_code=True, + ) + self.processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) + self.temperature = temperature + self.max_tokens = max_tokens + self.extract_summary = extract_summary + + def encode_image(self, image_path): + mime_type, _ = guess_type(image_path) + if mime_type is None: + mime_type = "image/jpeg" + image_format = mime_type.split("/")[-1].upper() if mime_type else "JPEG" + image = Image.open(image_path) + # Handle the alpha channel + if image.mode == "RGBA": + image = self._rgba_to_rgb(image) + + encoded_image = self._encode_image(image, image_format) + + return encoded_image + + def _encode_image(self, image, image_format): + with BytesIO() as output: + image.convert("RGB").save(output, format=image_format) + base64_encoded_data = base64.b64encode(output.getvalue()).decode("utf-8") + return base64_encoded_data + + @staticmethod + def _rgba_to_rgb(image): + background = Image.new("RGBA", image.size, (255, 255, 255, 255)) + return Image.alpha_composite(background, image).convert("RGB") + + def message_to_promptimg(self, message, dataset=None): + processed_message = [] + images = [] + for item in message: + if item['type'] == 'text': + if dataset in ["MMMU_DEV_VAL", "MMStar"]: + item['value'] = item['value'].replace( + "Please select the correct answer from the options above. \n", "" + ) + item['value'] += "Answer the preceding question. The last line of your response should follow this format: 'Answer: $\\boxed{LETTER}$' (without quotes), where LETTER is one of the options. Think step by step logically, considering all relevant information before answering." # noqa: E501 + processed_message.append({ + "type": "text", + "text": f"{item['value']}" + }) + elif item['type'] == 'image': + image_path = item['value'] + encoded_image = self.encode_image(image_path) + image = Image.open(BytesIO(base64.b64decode(encoded_image))) + image.load() + processed_message.append({ + "type": "image", + "image": image_path, + }) + images.append(image) + return processed_message, images + + def generate_inner(self, message, dataset=None): + prompt, images = self.message_to_promptimg(message, dataset=dataset) + messages = [ + {'role': 'user', 'content': prompt} + ] + text = self.processor.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt") + inputs = self.processor( + images=images, text=text, + return_tensors="pt", + padding=True, + truncation=True + ).to(self.model.device) + if self.temperature == 0.0: + generated_ids = self.model.generate(**inputs, max_new_tokens=self.max_tokens, do_sample=False) + else: + generated_ids = self.model.generate(**inputs, max_new_tokens=self.max_tokens, temperature=self.temperature) + generated_ids_trimmed = [ + out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) + ] + response = self.processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + )[0] + if self.extract_summary: + response = extract_summary(response) + if dataset in ["MMMU_DEV_VAL", "MMStar"]: + response = extract_boxed_content(response) + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/logics.py b/VLMEvalKit-sudoku/vlmeval/vlm/logics.py new file mode 100644 index 0000000000000000000000000000000000000000..bb55bea1377c21c3530384f1770a8a415889bf83 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/logics.py @@ -0,0 +1,73 @@ +import torch +from .base import BaseModel +from ..smp import * +from transformers import AutoModelForCausalLM, AutoProcessor + +try: + import av + from decord import VideoReader, cpu +except ImportError: + print("Please install pyav to use video processing functions.") + + +def move_to_device(batch, device): + new_batch = {} + for k, v in batch.items(): + if torch.is_tensor(v): + new_batch[k] = v.to(device) + else: + new_batch[k] = v + return new_batch + + +class Logics_Thinking(BaseModel): + INSTALL_REQ = True + INTERLEAVE = True + + def __init__(self, + model_path: str = "Logics-MLLM/Logics-Thinking", + **kwargs): + super().__init__() + + self.model = AutoModelForCausalLM.from_pretrained( + model_path, + torch_dtype="auto", + device_map="auto", + trust_remote_code=True, + ) + + self.processor = AutoProcessor.from_pretrained( + model_path, + trust_remote_code=True, + ) + self.stop_str = "<|im_end|>" + + def generate_inner_image(self, message): + text_prompt = "" + image_paths = [] + + for msg in message: + if msg["type"] == "text": + text_prompt += msg["value"] + elif msg["type"] == "image": + image_paths.append(msg["value"]) + + inputs = self.processor( + text=text_prompt, + images=image_paths, + return_tensors="pt" + ) + + DEVICE = self.model.device + inputs = move_to_device(inputs, DEVICE) + generated_ids = self.model.generate(**inputs) + text_outputs = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + text_outputs = text_outputs.strip() + + if text_outputs.endswith(self.stop_str): + text_outputs = text_outputs[:-len(self.stop_str)] + text_outputs = text_outputs.strip() + return text_outputs + + def generate_inner(self, message, dataset): + return self.generate_inner_image(message) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/minigpt4.py b/VLMEvalKit-sudoku/vlmeval/vlm/minigpt4.py new file mode 100644 index 0000000000000000000000000000000000000000..a4cc4b7929def6f4bf93f8caafed15eb8c4fa995 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/minigpt4.py @@ -0,0 +1,85 @@ +import torch +import sys +import os.path as osp +import warnings +from transformers import StoppingCriteriaList +from .base import BaseModel + + +class MiniGPT4(BaseModel): + + INSTALL_REQ = True + INTERLEAVE = False + + def __init__(self, + mode='v2', + root='/mnt/petrelfs/share_data/duanhaodong/MiniGPT-4/', + temperature=1, + max_out_len=512): + + if root is None: + warnings.warn( + 'Please set root to the directory of MiniGPT-4, which is cloned from here: ' + 'https://github.com/Vision-CAIR/MiniGPT-4. ' + ) + + if mode == 'v2': + cfg = 'minigptv2_eval.yaml' + elif mode == 'v1_7b': + cfg = 'minigpt4_7b_eval.yaml' + elif mode == 'v1_13b': + cfg = 'minigpt4_13b_eval.yaml' + else: + raise NotImplementedError + + self.mode = mode + self.temperature = temperature + self.max_out_len = max_out_len + self.root = root + this_dir = osp.dirname(__file__) + + self.cfg = osp.join(this_dir, 'misc', cfg) + sys.path.append(self.root) + + from omegaconf import OmegaConf + from minigpt4.common.registry import registry + from minigpt4.conversation.conversation import StoppingCriteriaSub, CONV_VISION_Vicuna0, CONV_VISION_minigptv2 + + device = torch.cuda.current_device() + self.device = device + + cfg_path = self.cfg + cfg = OmegaConf.load(cfg_path) + + model_cfg = cfg.model + model_cfg.device_8bit = device + model_cls = registry.get_model_class(model_cfg.arch) + model = model_cls.from_config(model_cfg) + model = model.to(device) + model.eval() + vis_processor_cfg = cfg.datasets.cc_sbu_align.vis_processor.train + vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg) + self.model = model + self.vis_processor = vis_processor + + self.CONV_VISION = CONV_VISION_minigptv2 if self.mode == 'v2' else CONV_VISION_Vicuna0 + stop_words_ids = [[835], [2277, 29937]] + stop_words_ids = [torch.tensor(ids).to(device) for ids in stop_words_ids] + self.stopping_criteria = StoppingCriteriaList([StoppingCriteriaSub(stops=stop_words_ids)]) + + def generate_inner(self, message, dataset=None): + from minigpt4.conversation.conversation import Chat + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + if self.mode == 'v2': + chat = Chat(self.model, self.vis_processor, device=self.device) + else: + chat = Chat(self.model, self.vis_processor, device=self.device, stopping_criteria=self.stopping_criteria) + + chat_state = self.CONV_VISION.copy() + img_list = [] + _ = chat.upload_img(image_path, chat_state, img_list) + chat.encode_img(img_list) + chat.ask(prompt, chat_state) + with torch.inference_mode(): + msg = chat.answer(conv=chat_state, img_list=img_list)[0] + return msg diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/minimonkey.py b/VLMEvalKit-sudoku/vlmeval/vlm/minimonkey.py new file mode 100644 index 0000000000000000000000000000000000000000..561430be975e2b09dbd311999f232d3e1555aa3e --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/minimonkey.py @@ -0,0 +1,492 @@ +import torch +from transformers import AutoTokenizer, AutoConfig, AutoModel, CLIPImageProcessor +import warnings +from PIL import Image +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE +import pandas as pd +import string +import torch.distributed as dist +import torchvision.transforms as T +import transformers + +from torchvision.transforms.functional import InterpolationMode +import re + + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + + +def build_transform(input_size): + MEAN, STD = IMAGENET_MEAN, IMAGENET_STD + transform = T.Compose([ + T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), + T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(mean=MEAN, std=STD) + ]) + return transform + + +def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): + best_ratio_diff = float('inf') + best_ratio = (1, 1) + area = width * height + for ratio in target_ratios: + target_aspect_ratio = ratio[0] / ratio[1] + ratio_diff = abs(aspect_ratio - target_aspect_ratio) + if ratio_diff < best_ratio_diff: + best_ratio_diff = ratio_diff + best_ratio = ratio + elif ratio_diff == best_ratio_diff: + if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: + best_ratio = ratio + return best_ratio + + +def dynamic_preprocess(image, min_num=5, max_num=6, image_size=448, use_thumbnail=False): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if + i * j <= max_num and i * j >= min_num) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio( + aspect_ratio, target_ratios, orig_width, orig_height, image_size) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images, target_aspect_ratio + + +def dynamic_preprocess2(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False, prior_aspect_ratio=None): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if + i * j <= max_num and i * j >= min_num) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + new_target_ratios = [] + if prior_aspect_ratio is not None: + for i in target_ratios: + if prior_aspect_ratio[0] % i[0] != 0 or prior_aspect_ratio[1] % i[1] != 0: + new_target_ratios.append(i) + else: + continue + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio( + aspect_ratio, new_target_ratios, orig_width, orig_height, image_size) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images + + +def load_image(image_file, input_size=448, min_num=1, max_num=6): + image = Image.open(image_file).convert('RGB') + transform = build_transform(input_size=input_size) + images, target_aspect_ratio = dynamic_preprocess( + image, image_size=input_size, use_thumbnail=True, min_num=min_num, max_num=max_num) + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values, target_aspect_ratio + + +def load_image2(image_file, input_size=448, target_aspect_ratio=(1, 1), min_num=1, max_num=6): + image = Image.open(image_file).convert('RGB') + transform = build_transform(input_size=input_size) + images = dynamic_preprocess2( + image, + image_size=input_size, + prior_aspect_ratio=target_aspect_ratio, + use_thumbnail=True, + min_num=min_num, + max_num=max_num) + + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values + + +# To revert changes +class MiniMonkey(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='mx262/MiniMokney', **kwargs): + assert model_path is not None + assert version_cmp(transformers.__version__, '4.36.2', 'ge') + + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False) + + # Regular expression to match the pattern 'Image' followed by a number, e.g. Image1 + self.pattern = r'Image(\d+)' + # Replacement pattern to insert a hyphen between 'Image' and the number, e.g. Image-1 + self.replacement = r'Image-\1' + + # Convert InternVL2 response to dataset format + # e.g. Image1 -> Image-1 + + # Regular expression to match the pattern 'Image-' followed by a number + self.reverse_pattern = r'Image-(\d+)' + # Replacement pattern to remove the hyphen (Image-1 -> Image1) + self.reverse_replacement = r'Image\1' + + self.device = 'cuda' + self.model = AutoModel.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + trust_remote_code=True, + load_in_8bit=False, + device_map='cuda').eval() + + self.image_size = self.model.config.vision_config.image_size + self.kwargs = kwargs + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + + def use_custom_prompt(self, dataset): + if dataset is None: + return False + if listinstr(['MMDU'], dataset): + # For Multi-Turn we don't have custom prompt + return False + else: + return True + + def build_multi_choice_prompt(self, line, dataset=None): + question = line['question'] + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + prompt += '\n请直接回答选项字母。' if cn_string( + prompt) else "\nAnswer with the option's letter from the given choices directly." + else: + prompt += '\n请直接回答问题。' if cn_string(prompt) else '\nAnswer the question directly.' + + return prompt + + def build_video_prompt(self, prompt, dataset=None, max_nframe=64): + for start in range(0, max_nframe, 8): + images_to_remove = ''.join([f'' for i in range(start + 1, start + 9)]) + prompt = prompt.replace(images_to_remove, '') + for i in range(max_nframe): + prompt = prompt.replace(f'', f'Frame{i + 1}') + if listinstr(['MMBench-Video'], dataset): + prompt = prompt.replace('\nAnswer:', '') + prompt += '\nAnswer the question using a single word or phrase.' + elif listinstr(['Video-MME'], dataset): + prompt = prompt.replace('\nAnswer:', '') + prompt += "\nAnswer with the option's letter from the given choices directly." + return prompt + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + kwargs_default = dict(do_sample=False, max_new_tokens=512, top_p=None, num_beams=1) + self.kwargs = kwargs_default + + if dataset is not None and listinstr(['MME'], dataset): + question = line['question'] + prompt = question + ' Answer the question using a single word or phrase.' + elif dataset is not None and listinstr(['HallusionBench'], dataset): + question = line['question'] + prompt = question + ' Please answer yes or no. Answer the question using a single word or phrase.' + elif dataset is not None and DATASET_TYPE(dataset) == 'MCQ': + prompt = self.build_multi_choice_prompt(line, dataset) + elif dataset is not None and DATASET_TYPE(dataset) == 'VQA': + if listinstr(['MathVista', 'MathVision'], dataset): + prompt = line['question'] + elif listinstr(['LLaVABench'], dataset): + question = line['question'] + prompt = question + '\nAnswer this question in detail.' + elif listinstr(['MMVet'], dataset): + prompt = line['question'] + else: + question = line['question'] + prompt = question + '\nAnswer the question using a single word or phrase.' + else: + prompt = line['question'] + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def set_max_num(self, dataset): + if dataset is None: + self.max_num = 12 + self.max_num2 = 7 + self.min_num = 4 + self.min_num2 = 3 + return + + if dataset is not None and listinstr(['ChartQA_TEST'], dataset): + self.max_num = 12 + self.max_num2 = 3 + elif dataset is not None and listinstr(['DocVQA_VAL', 'DocVQA_TEST', 'TextVQA_VAL'], dataset): + self.max_num = 23 + self.max_num2 = 15 + self.min_num = 14 + self.min_num2 = 5 + elif dataset is not None and listinstr(['InfoVQA_VAL', 'InfoVQA_TEST', 'SEEDBench_IMG'], dataset): + self.max_num = 23 + self.max_num2 = 5 + self.min_num = 15 + self.min_num2 = 3 + elif dataset is not None and listinstr(['OCRBench', 'POPE'], dataset): + self.max_num = 24 + self.max_num2 = 8 + self.min_num = 9 + self.min_num2 = 5 + elif dataset is not None and listinstr(['HallusionBench'], dataset): + self.max_num = 11 + self.max_num2 = 6 + self.min_num = 4 + self.min_num2 = 2 + elif dataset is not None and listinstr(['MME'], dataset): + self.max_num = 11 + self.max_num2 = 6 + self.min_num = 5 + self.min_num2 = 2 + elif dataset is not None and listinstr(['AI2D_TEST'], dataset): + self.max_num = 12 + self.max_num2 = 6 + self.min_num = 5 + self.min_num2 = 2 + elif dataset is not None and listinstr(['CCBench'], dataset): + self.max_num = 24 + self.max_num2 = 8 + self.min_num = 9 + self.min_num2 = 4 + elif dataset is not None and listinstr(['MMMU_DEV_VAL'], dataset): + self.max_num = 12 + self.max_num2 = 7 + self.min_num = 5 + self.min_num2 = 3 + else: + self.max_num = 12 + self.max_num2 = 7 + self.min_num = 4 + self.min_num2 = 3 + + def generate_v2(self, message, dataset=None): + image_num = len([x for x in message if x['type'] == 'image']) + if image_num == 1: + prompt = '\n' + '\n'.join([x['value'] for x in message if x['type'] == 'text']) + else: + prompt, image_idx = '', 1 + for x in message: + if x['type'] == 'text': + prompt += x['value'] + elif x['type'] == 'image': + prompt += f'' + image_idx += 1 + prompt = ' '.join([f': ' for i in range(image_num)]) + '\n' + prompt + + if dataset is not None and listinstr(['Video'], dataset): + prompt = self.build_video_prompt(prompt, dataset) + + if image_num > 1: + image_path = [x['value'] for x in message if x['type'] == 'image'] + num_patches_list = [] + pixel_values_list = [] + for image_idx, file_name in enumerate(image_path): + curr_pixel_values, target_aspect_ratio = load_image( + file_name, min_num=self.min_num, max_num=self.max_num) + curr_pixel_values = curr_pixel_values.cuda().to(torch.bfloat16) + curr_pixel_values2 = load_image2( + file_name, target_aspect_ratio=target_aspect_ratio, min_num=self.min_num2, max_num=self.max_num2) + curr_pixel_values2 = curr_pixel_values2.cuda().to(torch.bfloat16) + curr_pixel_values = torch.cat( + (curr_pixel_values[:-1], curr_pixel_values2[:-1], curr_pixel_values[-1:]), 0) + num_patches_list.append(curr_pixel_values.size(0)) + pixel_values_list.append(curr_pixel_values) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_num == 1: + image_path = [x['value'] for x in message if x['type'] == 'image'][0] + pixel_values, target_aspect_ratio = load_image(image_path, min_num=self.min_num, max_num=self.max_num) + pixel_values = pixel_values.cuda().to(torch.bfloat16) + pixel_values2 = load_image2( + image_path, target_aspect_ratio=target_aspect_ratio, min_num=self.min_num2, max_num=self.max_num2) + pixel_values2 = pixel_values2.cuda().to(torch.bfloat16) + pixel_values = torch.cat((pixel_values[:-1], pixel_values2[:-1], pixel_values[-1:]), 0) + num_patches_list = [pixel_values.size(0)] + else: + pixel_values = None + num_patches_list = [] + + with torch.no_grad(): + response = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + target_aspect_ratio=(1, 1), + num_patches_list=num_patches_list, + question=prompt, + generation_config=self.kwargs, + verbose=False + ) + return response + + def generate_inner(self, message, dataset=None): + self.set_max_num(dataset) + return self.generate_v2(message, dataset) + + def build_history(self, message): + # Global Variables + image_path = [] + image_cnt = 0 + + def concat_tilist(tilist): + nonlocal image_cnt # Declare image_cnt as nonlocal to modify it + prompt = '' + for item in tilist: + # Substitute the pattern in the text + if item['type'] == 'text': + prompt += re.sub(self.pattern, self.replacement, item['value']) + elif item['type'] == 'image': + image_cnt += 1 + prompt += '\n' + image_path.append(item['value']) + return prompt + + # Only previous messages + assert len(message) % 2 == 0 + history = [] + for i in range(len(message) // 2): + m1, m2 = message[2 * i], message[2 * i + 1] + assert m1['role'] == 'user' and m2['role'] == 'assistant' + history.append((concat_tilist(m1['content']), concat_tilist(m2['content']))) + + return history, image_path, image_cnt + + def chat_inner_v2(self, message, dataset=None): + + image_cnt = 0 + if len(message) > 1: + history, image_path, image_cnt = self.build_history(message[:-1]) + else: + history, image_path, image_cnt = None, [], 1 + current_msg = message[-1] + question = '' + + # If message is just text in the conversation + if len(current_msg['content']) == 1 and current_msg['content'][0]['type'] == 'text': + question = current_msg['content'][0]['value'] + question = re.sub(self.pattern, self.replacement, question) # Fix pattern as per InternVL + else: + for msg in current_msg['content']: + if msg['type'] == 'text': + question += re.sub(self.pattern, self.replacement, msg['value']) + elif msg['type'] == 'image': + image_cnt += 1 + question += '\n' + image_path.append(msg['value']) + + if image_cnt > 1: + num_patches_list = [] + pixel_values_list = [] + for image_idx, file_name in enumerate(image_path): + curr_pixel_values, target_aspect_ratio = load_image( + file_name, min_num=self.min_num, max_num=self.max_num) + curr_pixel_values = curr_pixel_values.cuda().to(torch.bfloat16) + curr_pixel_values2 = load_image2( + file_name, target_aspect_ratio=target_aspect_ratio, min_num=self.min_num2, max_num=self.max_num2) + curr_pixel_values2 = curr_pixel_values2.cuda().to(torch.bfloat16) + curr_pixel_values = torch.cat( + (curr_pixel_values[:-1], curr_pixel_values2[:-1], curr_pixel_values[-1:]), 0) + num_patches_list.append(curr_pixel_values.size(0)) + pixel_values_list.append(curr_pixel_values) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_cnt == 1: + pixel_values, target_aspect_ratio = load_image(image_path, min_num=self.min_num, max_num=self.max_num) + pixel_values = pixel_values.cuda().to(torch.bfloat16) + pixel_values2 = load_image2( + image_path, target_aspect_ratio=target_aspect_ratio, min_num=self.min_num2, max_num=self.max_num2) + pixel_values2 = pixel_values2.cuda().to(torch.bfloat16) + pixel_values = torch.cat((pixel_values[:-1], pixel_values2[:-1], pixel_values[-1:]), 0) + num_patches_list = [pixel_values.size(0)] + else: + pixel_values = None + num_patches_list = [] + + response, history = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + target_aspect_ratio=target_aspect_ratio, + num_patches_list=num_patches_list, + question=question, + generation_config=self.kwargs, + history=history, + return_history=True + ) + + response = re.sub(self.reverse_pattern, self.reverse_replacement, response) + + return response + + def chat_inner(self, message, dataset=None): + self.set_max_num(dataset) + kwargs_default = dict(do_sample=False, max_new_tokens=512, top_p=None, num_beams=1) + self.kwargs = kwargs_default + return self.chat_inner_v2(message, dataset) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/mixsense.py b/VLMEvalKit-sudoku/vlmeval/vlm/mixsense.py new file mode 100644 index 0000000000000000000000000000000000000000..947084479bf9d52fcb4a13c455c179910075e521 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/mixsense.py @@ -0,0 +1,46 @@ +import torch +import transformers +from transformers import AutoModelForCausalLM, AutoTokenizer +from PIL import Image +import warnings + +from .base import BaseModel +from ..smp import * + + +class LLama3Mixsense(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='Zero-Vision/Llama-3-MixSenseV1_1', **kwargs): + assert model_path is not None + transformers.logging.set_verbosity_error() + transformers.logging.disable_progress_bar() + warnings.filterwarnings('ignore') + self.tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True + ) + self.model = AutoModelForCausalLM.from_pretrained( + model_path, trust_remote_code=True, device_map="cuda" + ).eval() + self.kwargs = kwargs + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message) + input_ids = self.model.text_process(prompt, self.tokenizer).to(device='cuda') + image = Image.open(image_path).convert('RGB') + image_tensor = self.model.image_process([image]).to(dtype=self.model.dtype, device='cuda') + # generate + with torch.inference_mode(): + output_ids = self.model.generate( + input_ids, + images=image_tensor, + max_new_tokens=2048, + use_cache=True, + eos_token_id=[ + self.tokenizer.eos_token_id, + self.tokenizer.convert_tokens_to_ids(['<|eot_id|>'])[0], + ], + ) + return self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/mmalaya.py b/VLMEvalKit-sudoku/vlmeval/vlm/mmalaya.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed9ba8d1388f9fa88d1c376c50b82b85b80e29b --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/mmalaya.py @@ -0,0 +1,342 @@ +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel +import warnings +from .base import BaseModel +from PIL import Image +from ..smp import * +from ..dataset import DATASET_TYPE +import pandas as pd +import string +import torchvision.transforms as T +import transformers + +from torchvision.transforms.functional import InterpolationMode + + +class MMAlaya(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='DataCanvas/MMAlaya', **kwargs): + assert model_path is not None + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True + ) + model = AutoModelForCausalLM.from_pretrained( + model_path, device_map="cuda", trust_remote_code=True + ).eval() + # need initialize tokenizer + model.initialize_tokenizer(self.tokenizer) + self.model = model + + self.kwargs = kwargs + warnings.warn( + f'Following kwargs received: {self.kwargs}, will use as generation config. ' + ) + torch.cuda.empty_cache() + + def generate_inner(self, message, dataset=None): + # read image + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + image = Image.open(image_path).convert('RGB') + # tokenize prompt, and proprecess image + input_ids, image_tensor, stopping_criteria = self.model.prepare_for_inference( + prompt, self.tokenizer, image, return_tensors='pt' + ) + with torch.inference_mode(): + output_ids = self.model.generate( + inputs=input_ids.cuda(), + images=image_tensor.cuda(), + do_sample=False, + max_new_tokens=512, + num_beams=1, + use_cache=True, + stopping_criteria=[stopping_criteria], + ) + # truncate input_ids in generate_ids and then decode to text + input_token_len = input_ids.shape[1] + response = self.tokenizer.batch_decode( + output_ids[:, input_token_len:].cpu(), + skip_special_tokens=True, + clean_up_tokenization_spaces=False, + )[0].strip() + return response + + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + + +def build_transform(input_size): + MEAN, STD = IMAGENET_MEAN, IMAGENET_STD + transform = T.Compose( + [ + T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), + T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(mean=MEAN, std=STD), + ] + ) + return transform + + +def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): + best_ratio_diff = float('inf') + best_ratio = (1, 1) + area = width * height + for ratio in target_ratios: + target_aspect_ratio = ratio[0] / ratio[1] + ratio_diff = abs(aspect_ratio - target_aspect_ratio) + if ratio_diff < best_ratio_diff: + best_ratio_diff = ratio_diff + best_ratio = ratio + elif ratio_diff == best_ratio_diff: + if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: + best_ratio = ratio + return best_ratio + + +def dynamic_preprocess( + image, min_num=1, max_num=6, image_size=448, use_thumbnail=False +): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) + for n in range(min_num, max_num + 1) + for i in range(1, n + 1) + for j in range(1, n + 1) + if i * j <= max_num and i * j >= min_num + ) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio( + aspect_ratio, target_ratios, orig_width, orig_height, image_size + ) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size, + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images + + +def load_image(image_file, input_size=448, max_num=6, upscale=False): + image = Image.open(image_file).convert('RGB') + if upscale: + image = image.resize((image.width * 2, image.height * 2), Image.BILINEAR) + transform = build_transform(input_size=input_size) + images = dynamic_preprocess( + image, image_size=input_size, use_thumbnail=True, max_num=max_num + ) + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values + + +class MMAlaya2(BaseModel): + """ + This implementation fine-tunes 20 LoRA modules based on the InternVL-Chat-V1-5 model. + The fine-tuned LoRA modules are then merged with the InternVL-Chat-V1-5 model + using the PEFT model merging method, TIES. + The code is based on the implementation in `vlmeval/vlm/internvl_chat.py`. + """ + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__( + self, + model_path='DataCanvas/MMAlaya2', + load_in_8bit=False, + **kwargs, + ): + assert model_path is not None + assert version_cmp(transformers.__version__, '4.36.2', 'ge') + + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True, use_fast=False + ) + + # Regular expression to match the pattern "Image" followed by a number, e.g. Image1 + self.pattern = r'Image(\d+)' + # Replacement pattern to insert a hyphen between "Image" and the number, e.g. Image-1 + self.replacement = r'Image-\1' + + # Convert InternVL2 response to dataset format + # e.g. Image1 -> Image-1 + + # Regular expression to match the pattern "Image-" followed by a number + self.reverse_pattern = r'Image-(\d+)' + # Replacement pattern to remove the hyphen (Image-1 -> Image1) + self.reverse_replacement = r'Image\1' + + self.model = AutoModel.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + trust_remote_code=True, + load_in_8bit=load_in_8bit, + device_map="cuda" + ).eval() + + self.image_size = self.model.config.vision_config.image_size + + kwargs_default = dict( + do_sample=False, max_new_tokens=1024, top_p=None, num_beams=1 + ) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + warnings.warn( + f'Following kwargs received: {self.kwargs}, will use as generation config. ' + ) + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(['MMDU', 'MME-RealWorld', 'MME-RealWorld-CN'], dataset): + # For Multi-Turn we don't have custom prompt + return False + else: + return True + + def build_multi_choice_prompt(self, line, dataset=None): + question = line['question'] + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + prompt += ( + '\n请直接回答选项字母。' + if cn_string(prompt) + else "\nAnswer with the option's letter from the given choices directly." + ) + else: + prompt += ( + '\n请直接回答问题。' + if cn_string(prompt) + else '\nAnswer the question directly.' + ) + + return prompt + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + + if dataset is not None and listinstr(['MME'], dataset): + question = line['question'] + prompt = question + ' Answer the question using a single word or phrase.' + elif dataset is not None and listinstr(['HallusionBench'], dataset): + question = line['question'] + prompt = ( + question + + ' Please answer yes or no. Answer the question using a single word or phrase.' + ) + elif dataset is not None and DATASET_TYPE(dataset) == 'MCQ': + prompt = self.build_multi_choice_prompt(line, dataset) + elif dataset is not None and DATASET_TYPE(dataset) == 'VQA': + if listinstr(['MathVista', 'MathVision', 'MathVerse'], dataset): + prompt = line['question'] + elif listinstr(['LLaVABench'], dataset): + question = line['question'] + prompt = question + '\nAnswer this question in detail.' + elif listinstr(['MMVet'], dataset): + prompt = line['question'] + else: + question = line['question'] + prompt = question + '\nAnswer the question using a single word or phrase.' + else: + prompt = line['question'] + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def set_max_num(self, dataset): + if dataset is not None and listinstr(['ChartQA_TEST', 'MMMU_DEV_VAL'], dataset): + self.max_num = 12 + elif dataset is not None and listinstr(['DocVQA_VAL', 'DocVQA_TEST'], dataset): + self.max_num = 18 + elif dataset is not None and listinstr( + ['InfoVQA_VAL', 'InfoVQA_TEST', 'OCRBench'], dataset + ): + self.max_num = 24 + elif dataset is not None and listinstr( + ['MMBench-Video', 'Video-MME', 'Video'], dataset + ): + self.max_num = 1 + else: + self.max_num = 6 + + def generate_inner(self, message, dataset=None): + self.set_max_num(dataset) + image_num = len([x for x in message if x['type'] == 'image']) + prompt = '\n'.join([x['value'] for x in message if x['type'] == 'text']) + + if image_num > 1: + image_path = [x['value'] for x in message if x['type'] == 'image'] + pixel_values_list = [] + max_num = max(1, self.max_num // image_num) + for file_name in image_path: + pixel_values_list.append(load_image(file_name, max_num=max_num).cuda().to(torch.bfloat16)) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_num == 1: + image_path = [x['value'] for x in message if x['type'] == 'image'][0] + pixel_values = ( + load_image(image_path, max_num=self.max_num).cuda().to(torch.bfloat16) + ) + else: + pixel_values = None + with torch.no_grad(): + response = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + question=prompt, + generation_config=self.kwargs, + # verbose=False, + ) + return response + + +if __name__ == '__main__': + model = MMAlaya2(max_new_tokens=1024, do_sample=False) + response = model.generate_inner( + [ + {'type': 'image', 'value': './assets/apple.jpg'}, + {'type': 'text', 'value': '请详细描述一下这张图片。'}, + ] + ) + print(response) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/monkey.py b/VLMEvalKit-sudoku/vlmeval/vlm/monkey.py new file mode 100644 index 0000000000000000000000000000000000000000..f3804777f66f42c367287b2e9584491c6149991a --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/monkey.py @@ -0,0 +1,165 @@ +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer +import warnings +from .base import BaseModel +from ..dataset import DATASET_TYPE + + +class Monkey(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='echo840/Monkey', **kwargs): + assert model_path is not None + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + model = AutoModelForCausalLM.from_pretrained(model_path, device_map='cpu', trust_remote_code=True).eval() + self.model = model.cuda() + self.kwargs = kwargs + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + torch.cuda.empty_cache() + + def generate_vanilla(self, image_path, prompt): + cur_prompt = f'{image_path} {prompt} Answer: ' + input_ids = self.tokenizer(cur_prompt, return_tensors='pt', padding='longest') + attention_mask = input_ids.attention_mask + input_ids = input_ids.input_ids + + output_ids = self.model.generate( + input_ids=input_ids.cuda(), + attention_mask=attention_mask.cuda(), + do_sample=False, + num_beams=1, + max_new_tokens=512, + min_new_tokens=1, + length_penalty=1, + num_return_sequences=1, + output_hidden_states=True, + use_cache=True, + pad_token_id=self.tokenizer.eod_id, + eos_token_id=self.tokenizer.eod_id, + ) + response = self.tokenizer.decode( + output_ids[0][input_ids.size(1):].cpu(), + skip_special_tokens=True + ).strip() + return response + + def generate_multichoice(self, image_path, prompt): + cur_prompt = f'{image_path} \n {prompt} Answer: ' + input_ids = self.tokenizer(cur_prompt, return_tensors='pt', padding='longest') + attention_mask = input_ids.attention_mask + input_ids = input_ids.input_ids + + output_ids = self.model.generate( + input_ids=input_ids.cuda(), + attention_mask=attention_mask.cuda(), + do_sample=False, + num_beams=1, + max_new_tokens=10, + min_new_tokens=1, + length_penalty=1, + num_return_sequences=1, + output_hidden_states=True, + use_cache=True, + pad_token_id=self.tokenizer.eod_id, + eos_token_id=self.tokenizer.eod_id, + ) + response = self.tokenizer.decode( + output_ids[0][input_ids.size(1):].cpu(), + skip_special_tokens=True + ).strip() + return response + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + if dataset is None: + return self.generate_vanilla(image_path, prompt) + assert isinstance(dataset, str) + if DATASET_TYPE(dataset) == 'MCQ' or DATASET_TYPE(dataset) == 'Y/N' or dataset == 'HallusionBench': + return self.generate_multichoice(image_path, prompt) + else: + return self.generate_vanilla(image_path, prompt) + + +class MonkeyChat(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='echo840/Monkey-Chat', **kwargs): + assert model_path is not None + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + model = AutoModelForCausalLM.from_pretrained(model_path, device_map='cpu', trust_remote_code=True).eval() + self.model = model.cuda() + self.kwargs = kwargs + + self.tokenizer.padding_side = 'left' + self.tokenizer.pad_token_id = self.tokenizer.eod_id + + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + torch.cuda.empty_cache() + + def generate_vanilla(self, image_path, prompt): + cur_prompt = f'{image_path} {prompt} Answer: ' + input_ids = self.tokenizer(cur_prompt, return_tensors='pt', padding='longest') + attention_mask = input_ids.attention_mask + input_ids = input_ids.input_ids + + output_ids = self.model.generate( + input_ids=input_ids.cuda(), + attention_mask=attention_mask.cuda(), + do_sample=False, + num_beams=1, + max_new_tokens=512, + min_new_tokens=1, + length_penalty=1, + num_return_sequences=1, + output_hidden_states=True, + use_cache=True, + pad_token_id=self.tokenizer.eod_id, + eos_token_id=self.tokenizer.eod_id, + ) + response = self.tokenizer.decode( + output_ids[0][input_ids.size(1):].cpu(), + skip_special_tokens=True + ).strip() + return response + + def generate_multichoice(self, image_path, prompt): + cur_prompt = f'{image_path} \n {prompt} Answer: ' + input_ids = self.tokenizer(cur_prompt, return_tensors='pt', padding='longest') + attention_mask = input_ids.attention_mask + input_ids = input_ids.input_ids + + output_ids = self.model.generate( + input_ids=input_ids.cuda(), + attention_mask=attention_mask.cuda(), + do_sample=False, + num_beams=1, + max_new_tokens=10, + min_new_tokens=1, + length_penalty=1, + num_return_sequences=1, + output_hidden_states=True, + use_cache=True, + pad_token_id=self.tokenizer.eod_id, + eos_token_id=self.tokenizer.eod_id, + ) + response = self.tokenizer.decode( + output_ids[0][input_ids.size(1):].cpu(), + skip_special_tokens=True + ).strip() + return response + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + if dataset is None: + return self.generate_vanilla(image_path, prompt) + assert isinstance(dataset, str) + if DATASET_TYPE(dataset) == 'MCQ' or DATASET_TYPE(dataset) == 'Y/N' or dataset == 'HallusionBench': + return self.generate_multichoice(image_path, prompt) + else: + return self.generate_vanilla(image_path, prompt) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/moondream.py b/VLMEvalKit-sudoku/vlmeval/vlm/moondream.py new file mode 100644 index 0000000000000000000000000000000000000000..9ee05a31ee848cd855a117cb6e888a4a4957f85e --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/moondream.py @@ -0,0 +1,218 @@ +import torch +import re +from PIL import Image +from abc import abstractproperty +import sys +import os.path as osp +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE +import copy + + +class Moondream1(BaseModel): + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path="vikhyatk/moondream1", **kwargs): + try: + from transformers import ( + AutoModelForCausalLM, + CodeGenTokenizerFast as Tokenizer, + ) + except Exception as e: + logging.critical( + "Please install Transformers version 4.36.2 by running: 'pip install transformers==4.36.2', " + "please intall torchvision>=0.16." + ) + raise e + + assert osp.exists(model_path) or splitlen(model_path) == 2 + + self.model = AutoModelForCausalLM.from_pretrained( + model_path, + trust_remote_code=True, + torch_dtype=torch.float16, + device_map="cuda", + ) + self.tokenizer = Tokenizer.from_pretrained(model_path) + + default_kwargs = dict(max_new_tokens=512) + default_kwargs.update(kwargs) + self.kwargs = default_kwargs + + warnings.warn(f"Following kwargs received: {self.kwargs}, will use as generation config. ") + torch.cuda.empty_cache() + + def generate_inner(self, message, dataset=None): + prompt, img = self.message_to_promptimg(message) + enc_image = self.model.encode_image(Image.open(img)) + + prompt_wtmpl = f"\n\nQuestion: {prompt}\n\nAnswer:" + answer = self.model.generate( + enc_image, + prompt_wtmpl, + eos_text="", + tokenizer=self.tokenizer, + **self.kwargs, + )[0] + cleaned_answer = re.sub("<$", "", re.sub("END$", "", answer)).strip() + return cleaned_answer + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(["MMMU"], dataset): + return False + if DATASET_TYPE(dataset) == "MCQ" or dataset in [ + "MMVet", + ]: + return True + + return False + + def build_prompt(self, line, dataset=None): + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + tgt_path = self.dump_image(line, dataset) + question = line["question"] + if dataset == "MMVet": + prompt = question + "\nAnswer the question directly. " + elif DATASET_TYPE(dataset) == "MCQ": + options = {cand: line[cand] for cand in string.ascii_uppercase if cand in line and not pd.isna(line[cand])} + options_prompt = "" + for key, item in options.items(): + options_prompt += f"{key}. {item}\n" + + hint = line["hint"] if ("hint" in line and not pd.isna(line["hint"])) else None + prompt = f"Hint: {hint}\n" if hint is not None else "" + prompt += f"{question}\n" + prompt += ( + f"{options_prompt}\nAnswer with the option’s letter from the given choices directly. " + if len(options) + else "Answer the question directly. " + ) + else: + raise NotImplementedError + + message = [dict(type="text", value=prompt)] + message.extend([dict(type="image", value=s) for s in tgt_path]) + return message + + +class Moondream2(BaseModel): + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path="vikhyatk/moondream2", revision="2025-01-09", **kwargs): + try: + from transformers import AutoModelForCausalLM, AutoTokenizer + except Exception as e: + logging.critical( + """Please install Transformers version 4.44 by running: "pip install transformers==4.44.0", + please intall torchvision>=0.16.""" + ) + raise e + + assert osp.exists(model_path) or splitlen(model_path) == 2 + + self.model = AutoModelForCausalLM.from_pretrained( + model_path, + trust_remote_code=True, + torch_dtype=torch.float16, + device_map={"": "cuda"}, + revision=revision, + ) + + self.tokenizer = AutoTokenizer.from_pretrained(model_path) + + default_kwargs = dict(max_new_tokens=512) + default_kwargs.update(kwargs) + self.kwargs = default_kwargs + + warnings.warn(f"Following kwargs received: {self.kwargs}, will use as generation config. ") + torch.cuda.empty_cache() + + def generate_inner(self, message, dataset=None): + prompt, img = self.message_to_promptimg(message) + enc_image = self.model.encode_image(Image.open(img)) + print(f"prompt for {dataset} -> ", prompt) + + answer = self.model.query(enc_image, prompt)["answer"] + cleaned_answer = answer.strip() + + return cleaned_answer + + def use_custom_prompt(self, dataset): + assert dataset is not None + + if listinstr(["MMMU"], dataset): + return False + if DATASET_TYPE(dataset) == "MCQ": + return True + elif dataset in [ + "ChartQA_TEST", + "TextVQA_VAL", + "DocVQA_VAL", + "POPE", + "RealWorldQA", + "TallyQA", + "CountbenchQA", + "MMVet", + ]: + return True + else: + return False + + def build_prompt(self, line, dataset=None): + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + tgt_path = self.dump_image(line, dataset) + question = line["question"] + + if dataset == "ChartQA_TEST": + prompt = ( + "Analyze the chart carefully, consider both visual features and data values," + " and provide a precise answer without any additional explanation or formatting. " + + question + ) + elif dataset == "TextVQA_VAL": + prompt = ( + "Read the text in the image and provide a brief lowercase answer. " + "Respond 'unanswerable' only if there is no plausible answer. " + + question + ) + elif dataset == "DocVQA_VAL": + prompt = question + " The answer should be a short text span taken verbatim from the document." + elif dataset == "POPE": + prompt = f"{question}\nAnswer yes or no." + elif dataset == "RealWorldQA": + prompt = question + elif dataset == "TallyQA" or dataset == "CountbenchQA": + prompt = ( + "Look at the image carefully and count the objects. " + "Answer with just a number, without any additional text. " + + question + ) + + elif dataset == "MMVet": + prompt = question + "\nAnswer the question directly. " + elif DATASET_TYPE(dataset) == "MCQ": + options = {cand: line[cand] for cand in string.ascii_uppercase if cand in line and not pd.isna(line[cand])} + options_prompt = "" + for key, item in options.items(): + options_prompt += f"{key}. {item}\n" + + hint = line["hint"] if ("hint" in line and not pd.isna(line["hint"])) else None + prompt = f"Hint: {hint}\n" if hint is not None else "" + prompt += f"{question}\n" + prompt += ( + f"{options_prompt}\nAnswer with the option’s letter from the given choices directly. " + if len(options) + else "Answer the question directly. " + ) + else: + raise NotImplementedError + + message = [dict(type="text", value=prompt)] + message.extend([dict(type="image", value=s) for s in tgt_path]) + return message diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl2.py b/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl2.py new file mode 100644 index 0000000000000000000000000000000000000000..30d6adc72dbdacc02c45c409d2890ce49988358c --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl2.py @@ -0,0 +1,126 @@ +import sys +import torch +from PIL import Image +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE + + +class mPLUG_Owl2(BaseModel): + + INSTALL_REQ = True + INTERLEAVE = False + + def __init__(self, model_path='MAGAer13/mplug-owl2-llama2-7b', **kwargs): + try: + from mplug_owl2.model.builder import load_pretrained_model + from mplug_owl2.mm_utils import get_model_name_from_path + except Exception as e: + logging.critical('Please install mPLUG_Owl2 before using mPLUG_Owl2. ') + raise e + + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model( + model_path, None, model_name, load_8bit=False, load_4bit=False, device='cpu') + + self.model = model.cuda() + self.device = self.model.device + self.image_processor = image_processor + tokenizer.padding_side = 'left' + tokenizer.pad_token_id = tokenizer.eos_token_id + self.tokenizer = tokenizer + self.context_len = context_len + + kwargs_default = dict( + max_new_tokens=512, do_sample=False, num_beams=1, + min_new_tokens=1, length_penalty=1, num_return_sequences=1) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(['MMMU'], dataset): + return False + if DATASET_TYPE(dataset) == 'MCQ' or dataset == 'MMVet': + return True + return False + + def build_prompt(self, line, dataset=None): + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + tgt_path = self.dump_image(line, dataset) + question = line['question'] + if dataset == 'MMVet': + prompt = question + '\nAnswer the question directly. ' + elif DATASET_TYPE(dataset) == 'MCQ': + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = '' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = f'Hint: {hint}\n' if hint is not None else '' + prompt += f'{question}\n' + prompt += ( + f'{options_prompt}\nAnswer with the option’s letter from the given choices directly. ' + if len(options) else 'Answer the question directly. ' + ) + else: + raise NotImplementedError + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def generate_inner(self, message, dataset=None): + from mplug_owl2.constants import IMAGE_TOKEN_INDEX + from mplug_owl2.mm_utils import process_images, tokenizer_image_token + kwargs = cp.deepcopy(self.kwargs) + if dataset in ['MMVet', 'LLaVABench']: + kwargs['length_penalty'] = 0 + elif dataset is not None and DATASET_TYPE(dataset) == 'VQA': + kwargs['length_penalty'] = 0 + elif dataset is not None and DATASET_TYPE(dataset) == 'MCQ': + kwargs['max_new_tokens'] = 10 + num_images = len([x for x in message if x['type'] == 'image']) + assert num_images >= 0 + prompt_full = 'USER: ' + images = [] + if num_images == 1: + prompt, image = self.message_to_promptimg(message, dataset=dataset) + prompt_full += f'<|image|>{prompt} \nASSISTANT: ' + images.append(image) + else: + for msg in message: + if msg['type'] == 'image': + images.append(msg['value']) + prompt_full += '<|image|>' + elif msg['type'] == 'text': + prompt_full += msg['value'] + prompt_full += '\nASSISTANT: ' + + def preproc_image(fname): + image = Image.open(fname).convert('RGB') + max_edge = max(image.size) + image = image.resize((max_edge, max_edge)) + return image + images = [preproc_image(fname) for fname in images] + image_tensor = process_images(images, self.image_processor) + image_tensor = image_tensor.to(self.device, dtype=torch.float16) + input_ids = tokenizer_image_token( + prompt_full, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device) + + with torch.inference_mode(): + output_ids = self.model.generate( + input_ids=input_ids, + images=image_tensor, + output_hidden_states=True, + use_cache=True, + **kwargs) + answer = self.tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip() + return answer.split('')[0] diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl3.py b/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl3.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5295cdbfab5918bf45c8493da2007d467bdb2d --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/mplug_owl3.py @@ -0,0 +1,336 @@ +import torch +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE +from torchvision import transforms +from transformers import AutoTokenizer, AutoModel + +import io +import random +import numpy as np +import math + + +def get_frame_indices(num_frames, vlen, sample='rand', fix_start=None, input_fps=1, max_num_frames=-1): + if sample in ['rand', 'middle']: + acc_samples = min(num_frames, vlen) + # split the video into `acc_samples` intervals, and sample from each interval. + intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int) + ranges = [] + for idx, interv in enumerate(intervals[:-1]): + ranges.append((interv, intervals[idx + 1] - 1)) + if sample == 'rand': + try: + frame_indices = [random.choice(range(x[0], x[1])) for x in ranges] + except: + frame_indices = np.random.permutation(vlen)[:acc_samples] + frame_indices.sort() + frame_indices = list(frame_indices) + elif fix_start is not None: + frame_indices = [x[0] + fix_start for x in ranges] + elif sample == 'middle': + frame_indices = [(x[0] + x[1]) // 2 for x in ranges] + else: + raise NotImplementedError + + if len(frame_indices) < num_frames: # padded with last frame + padded_frame_indices = [frame_indices[-1]] * num_frames + padded_frame_indices[:len(frame_indices)] = frame_indices + frame_indices = padded_frame_indices + + elif 'fps' in sample: # fps0.5, sequentially sample frames at 0.5 fps + output_fps = float(sample[3:]) + duration = float(vlen) / input_fps + delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents + frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta) + frame_indices = np.around(frame_seconds * input_fps).astype(int) + frame_indices = [e for e in frame_indices if e < vlen] + if max_num_frames > 0 and len(frame_indices) > max_num_frames: + frame_indices = frame_indices[:max_num_frames] + # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames) + elif 'interval' in sample: + if num_frames == 1: + frame_indices = [random.randint(0, vlen - 1)] + else: + # transform FPS + interval = 8 + clip_length = num_frames * interval * input_fps / 30 + max_idx = max(vlen - clip_length, 0) + start_idx = random.uniform(0, max_idx) + end_idx = start_idx + clip_length - 1 + + frame_indices = torch.linspace(start_idx, end_idx, num_frames) + frame_indices = torch.clamp(frame_indices, 0, vlen - 1).long().tolist() + else: + raise ValueError + return frame_indices + + +def get_frame_indices_start_end(num_frames, vlen, fps, start_time, end_time): + start_idx = max(int(fps * start_time), 0) if start_time is not None and not math.isnan(start_time) else 0 + end_idx = min(int(fps * end_time), vlen) if end_time is not None and not math.isnan(end_time) else vlen + clip_len = end_idx - start_idx + + acc_samples = min(num_frames, clip_len) + # split the video into `acc_samples` intervals, and sample from each interval. + intervals = np.linspace(start=start_idx, stop=end_idx, num=acc_samples + 1).astype(int) + ranges = [] + for idx, interv in enumerate(intervals[:-1]): + ranges.append((interv, intervals[idx + 1] - 1)) + + try: + frame_indices = [random.choice(range(x[0], x[1])) for x in ranges] + except: + frame_indices = np.random.permutation(list(range(start_idx, end_idx)))[:acc_samples] + frame_indices.sort() + frame_indices = list(frame_indices) + + if len(frame_indices) < num_frames: # padded with last frame + padded_frame_indices = [frame_indices[-1]] * num_frames + padded_frame_indices[:len(frame_indices)] = frame_indices + frame_indices = padded_frame_indices + + return frame_indices + + +def read_frames_decord( + video_path, width=None, height=None, + num_frames=8, sample='rand', fix_start=None, + max_num_frames=-1, start_time=None, end_time=None +): + import decord + decord.bridge.set_bridge('torch') + if video_path.lower().endswith('.webm'): + # a workaround for webm, large/auto num_threads will cause error. + num_threads = 2 + else: + num_threads = 0 + + if width is not None and height is not None: + video_reader = decord.VideoReader(video_path, width=width, height=height, num_threads=num_threads) + else: + video_reader = decord.VideoReader(video_path, num_threads=num_threads) + vlen = len(video_reader) + fps = video_reader.get_avg_fps() + if start_time and end_time: + frame_indices = get_frame_indices_start_end( + num_frames, vlen, fps, start_time, end_time + ) + else: + frame_indices = get_frame_indices( + num_frames, vlen, sample=sample, fix_start=fix_start, + input_fps=fps, max_num_frames=max_num_frames + ) + frames = video_reader.get_batch(frame_indices) + if isinstance(frames, torch.Tensor): + frames = frames.numpy() # (T, H, W, C), torch.uint8 + else: + print(frames.shape) + frames = frames.asnumpy() + timestamp = { + 'num_frames': len(frame_indices), + 'timestamp': ', '.join([str(round(f / fps, 1)) for f in frame_indices]) + } + return frames, timestamp + + +class mPLUG_Owl3(BaseModel): + # No separate model module is required, but the dependencies must be met. + # https://github.com/X-PLUG/mPLUG-Owl/blob/main/mPLUG-Owl3/requirements.txt + INSTALL_REQ = True + INTERLEAVE = True + INSTALL_REQ_TXT = 'https://github.com/X-PLUG/mPLUG-Owl/blob/main/mPLUG-Owl3/requirements.txt' + + def __init__(self, model_path=None, **kwargs): + assert model_path is not None + self.tokenizer = AutoTokenizer.from_pretrained( + model_path + ) + + self.model = AutoModel.from_pretrained( + model_path, + attn_implementation='sdpa', + torch_dtype=torch.half, + trust_remote_code=True + ) + self.model.eval().cuda() + self.processor = self.model.init_processor(self.tokenizer) + self.logger = get_logger('mPLUG_Owl3') + if self.INSTALL_REQ: + self.logger.info( + f'Please remember to meet the requirements first\n' + f'Here: {self.INSTALL_REQ_TXT}' + ) + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(['MMMU'], dataset): + return False + if listinstr(['MVBench', 'MMVet'], dataset): + return True + return False + + def save_video_into_images(self, line, num_frames=16, dataset_class=None): + video_url = { + 'video': osp.join(line['prefix'], line['video']), + 'num_frames': num_frames, + 'bound': line.get('bound', None) + } + if osp.isdir(video_url['video']): + frame_paths = [] + max_frame = len(os.listdir(video_url['video'])) + fps = 3 + if video_url['bound']: + start, end = line['start'], line['end'] + else: + start, end = -100000, 100000 + start_idx = max(1, round(start * fps)) + end_idx = min(round(end * fps), max_frame) + seg_size = float(end_idx - start_idx) / num_frames + frame_indices = np.array([ + int(start_idx + (seg_size / 2) + np.round(seg_size * idx)) + for idx in range(num_frames) + ]) + + for frame_index in frame_indices: + img = os.path.join(video_url['video'], f'{frame_index:05d}.jpg') + frame_paths.append(img) + + return frame_paths + + if isinstance(video_url, dict): + if video_url['bound']: + start_time = line['start'] + end_time = line['end'] + else: + start_time = None + end_time = None + num_frames = video_url.get('num_frames', num_frames) + video_url = video_url['video'] + else: + start_time = None + end_time = None + video_url = str(video_url) + + if not osp.exists(video_url): # for MVBench_MP4 + video_url = osp.join(dataset_class.data_root, video_url) + video, timestamp = read_frames_decord( + video_url, num_frames=num_frames, sample='middle', start_time=start_time, end_time=end_time + ) + + to_pil = transforms.ToPILImage() + frames = [to_pil(video[ti]) for ti in range(video.shape[0])] + lmu_root = LMUDataRoot() + frame_root = osp.join(lmu_root, 'images', dataset_class.dataset_name, 'mplug_owl3') + frame_root = osp.join(frame_root, video_url.split('/')[-1].split('.')[0]) + os.makedirs(frame_root, exist_ok=True) + frame_tmpl = 'frame-{}-of-{}.jpg' + frame_paths = [osp.join(frame_root, frame_tmpl.format(i, num_frames)) for i in range(1, num_frames + 1)] + for im, pth in zip(frames, frame_paths): + if not osp.exists(pth): + im.save(pth) + + return frame_paths + + # Currently same to mPLUG_Owl2 + def build_prompt(self, line, dataset=None, num_frames=16, video_llm=False): + if not isinstance(dataset, str): + dataset_class = dataset + dataset = dataset_class.dataset_name + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + if dataset_class.MODALITY == 'VIDEO': + if listinstr(['MVBench'], dataset): + tgt_path = self.save_video_into_images(line, num_frames, dataset_class) + else: + tgt_path = dataset_class.save_video_into_images(line, num_frames) + if type(line['candidates']) is not list: + line['candidates'] = eval(line['candidates']) + for idx, c in enumerate(line['candidates']): + line[chr(ord('A') + idx)] = c + else: + tgt_path = self.dump_image(line, dataset) + question = line['question'] + if dataset == 'MMVet': + prompt = question + '\nAnswer the question directly. ' + elif listinstr(['MCQ', 'Video-MCQ'], DATASET_TYPE(dataset)): + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = '' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = f'Hint: {hint}\n' if hint is not None else '' + prompt += f'{question}\n' + prompt += ( + f'{options_prompt}\nAnswer with the option’s letter from the given choices directly. ' + if len(options) else 'Answer the question directly. ' + ) + else: + raise NotImplementedError + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def preproc_image(self, fname, dataset=None): + from PIL import Image + image = Image.open(fname).convert('RGB') + # resize to max_size + max_size = 448 * 16 + if max(image.size) > max_size and not listinstr(['MVBench'], dataset): + w, h = image.size + if w > h: + new_w = max_size + new_h = int(h * max_size / w) + else: + new_h = max_size + new_w = int(w * max_size / h) + image = image.resize((new_w, new_h), resample=Image.BICUBIC) + return image + + def generate_inner(self, message, dataset=None): + num_images = len([x for x in message if x['type'] == 'image']) + assert num_images >= 0 + + images = [] + prompt_full = '' + + for msg in message: + if msg['type'] == 'image': + images.append(msg['value']) + prompt_full += '<|image|>' + elif msg['type'] == 'text': + prompt_full += msg['value'] + + needed_messages = [ + {'role': 'user', 'content': prompt_full}, + {'role': 'assistant', 'content': ''} + ] + + images = [self.preproc_image(fname, dataset) for fname in images] + + inputs = self.processor(needed_messages, images=images, videos=None, cut_enable=False) + + inputs.to('cuda') + if listinstr(['MVBench'], dataset): + inputs.update({ + 'tokenizer': self.tokenizer, + 'max_new_tokens': 100, + 'decode_text': True, + 'do_sample': True, + 'top_k': 1, + }) + else: + inputs.update({ + 'tokenizer': self.tokenizer, + 'max_new_tokens': 1024, + 'decode_text': True, + }) + + g = self.model.generate(**inputs) + return g[0] diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/omnilmm.py b/VLMEvalKit-sudoku/vlmeval/vlm/omnilmm.py new file mode 100644 index 0000000000000000000000000000000000000000..12971cd7795d0bd0305186582ec6f9d6e0762a43 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/omnilmm.py @@ -0,0 +1,183 @@ +import torch +from PIL import Image +from transformers import AutoTokenizer + +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE + + +DEFAULT_IMAGE_TOKEN = '' +DEFAULT_IMAGE_PATCH_TOKEN = '' +DEFAULT_IM_START_TOKEN = '' +DEFAULT_IM_END_TOKEN = '' + + +def init_omni_lmm(model_path): + from omnilmm.model.omnilmm import OmniLMMForCausalLM + from omnilmm.utils import disable_torch_init + from omnilmm.model.utils import build_transform + + torch.backends.cuda.matmul.allow_tf32 = True + disable_torch_init() + tokenizer = AutoTokenizer.from_pretrained(model_path, model_max_length=2048) + + model = OmniLMMForCausalLM.from_pretrained( + model_path, tune_clip=True, torch_dtype=torch.bfloat16, device_map='cpu' + ) + model = model.to(device='cuda', dtype=torch.bfloat16) + + image_processor = build_transform( + is_train=False, input_size=model.model.config.image_size, std_mode='OPENAI_CLIP' + ) + + mm_use_im_start_end = getattr(model.config, 'mm_use_im_start_end', False) + assert mm_use_im_start_end + + tokenizer.add_tokens( + [DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], + special_tokens=True, + ) + + vision_config = model.model.vision_config + vision_config.im_patch_token = tokenizer.convert_tokens_to_ids( + [DEFAULT_IMAGE_PATCH_TOKEN] + )[0] + vision_config.use_im_start_end = mm_use_im_start_end + vision_config.im_start_token, vision_config.im_end_token = ( + tokenizer.convert_tokens_to_ids([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN]) + ) + image_token_len = model.model.config.num_query + + return model, image_processor, image_token_len, tokenizer + + +def expand_question_into_multimodal( + question_text, image_token_len, im_st_token, im_ed_token, im_patch_token +): + if '' in question_text[0]['content']: + question_text[0]['content'] = question_text[0]['content'].replace( + '', im_st_token + im_patch_token * image_token_len + im_ed_token + ) + else: + question_text[0]['content'] = ( + im_st_token + + im_patch_token * image_token_len + + im_ed_token + + '\n' + + question_text[0]['content'] + ) + return question_text + + +def wrap_question_for_omni_lmm(question, image_token_len, tokenizer): + from omnilmm.train.train_utils import omni_preprocess + + question = expand_question_into_multimodal( + question, + image_token_len, + DEFAULT_IM_START_TOKEN, + DEFAULT_IM_END_TOKEN, + DEFAULT_IMAGE_PATCH_TOKEN, + ) + + conversation = question + data_dict = omni_preprocess( + sources=[conversation], tokenizer=tokenizer, generation=True + ) + + data_dict = dict(input_ids=data_dict['input_ids'][0], labels=data_dict['labels'][0]) + return data_dict + + +class OmniLMM12B(BaseModel): + + INSTALL_REQ = True + INTERLEAVE = False + + def __init__(self, model_path, root, **kwargs) -> None: + sys.path.append(root) + model, img_processor, image_token_len, tokenizer = init_omni_lmm(model_path) + self.model = model + self.image_token_len = image_token_len + self.image_transform = img_processor + self.tokenizer = tokenizer + self.model.eval() + default_kwargs = dict( + max_new_tokens=512, + do_sample=False, + output_scores=True, + return_dict_in_generate=True, + repetition_penalty=1.1, + ) + default_kwargs.update(kwargs) + self.kwargs = default_kwargs + torch.cuda.empty_cache() + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + try: + image = Image.open(image_path).convert('RGB') + except: + logger = get_logger('OmniLMM Inference') + logger.error('Image Decode Error') + return 'Image Decode Error' + + msgs = [dict(role='user', content=prompt)] + input_ids = wrap_question_for_omni_lmm( + msgs, self.image_token_len, self.tokenizer + )['input_ids'] + input_ids = torch.as_tensor(input_ids) + image = self.image_transform(image) + + with torch.inference_mode(): + output = self.model.generate_vllm( + input_ids=input_ids.unsqueeze(0).cuda(), + images=image.unsqueeze(0).half().cuda(), + **self.kwargs, + ) + + response = self.tokenizer.decode( + output.sequences[0], skip_special_tokens=True + ) + response = response.strip() + return response + + def use_custom_prompt(self, dataset): + assert dataset is not None + if DATASET_TYPE(dataset) == 'MCQ': + return True + return False + + def build_prompt(self, line, dataset=None): + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + tgt_path = self.dump_image(line, dataset) + + question = line['question'] + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = 'Options:\n' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = '' + if hint is not None: + prompt += f'Hint: {hint}\n' + prompt += f'{question}\n' + if len(options): + prompt += options_prompt + prompt = ( + """ +Study the image carefully and pick the option associated with the correct answer. +Focus solely on selecting the option and avoid including any other content.\n +""" + + prompt + ) + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/open_flamingo.py b/VLMEvalKit-sudoku/vlmeval/vlm/open_flamingo.py new file mode 100644 index 0000000000000000000000000000000000000000..f3958266dd9117419dda8b6564a02a57159d3632 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/open_flamingo.py @@ -0,0 +1,100 @@ +import sys +import torch +from PIL import Image +import os.path as osp +import warnings +from .base import BaseModel +from ..smp import * +from huggingface_hub import snapshot_download + + +class OpenFlamingo(BaseModel): + + INSTALL_REQ = True + INTERLEAVE = True + + def __init__(self, + name, + mpt_pth=None, + ckpt_pth=None, + **kwargs): + + if mpt_pth is None: + raise ValueError( + 'Please set `mpt_pth` to the directory of MPT-7B, which is cloned from here: ' + 'https://huggingface.co/mosaicml/mpt-7b. ' + ) + raise ValueError + if ckpt_pth is None: + raise ValueError( + 'Please set `ckpt_pth` to the openflamingo ckpt, which is the `checkpoint.pt` file downloaded ' + 'from: https://huggingface.co/openflamingo/OpenFlamingo-9B-vitl-mpt7b/tree/main. ' + ) + else: + if osp.exists(ckpt_pth): + if ckpt_pth.endswith('checkpoint.pt'): + pass + elif osp.isdir(ckpt_pth): + ckpt_pth = osp.join(ckpt_pth, 'checkpoint.pt') + if not osp.exists(ckpt_pth): + raise ValueError(f'File {ckpt_pth} does not exist. ') + elif splitlen(ckpt_pth, '/') == 2: + cache_path = get_cache_path(ckpt_pth) + if cache_path is None: + snapshot_download(ckpt_pth) + cache_path = get_cache_path(ckpt_pth) + if cache_path is None: + raise ValueError(f'Directory {cache_path} does not exist. ') + else: + ckpt_pth = osp.join(cache_path, 'checkpoint.pt') + + self.name = name + assert name in ['v2'] + self.mpt_pth = mpt_pth + try: + from open_flamingo import create_model_and_transforms + except Exception as e: + logging.critical('Please first install open_flamingo to use OpenFlamingo') + raise e + + model, image_processor, tokenizer = create_model_and_transforms( + clip_vision_encoder_path='ViT-L-14', + clip_vision_encoder_pretrained='openai', + lang_encoder_path=mpt_pth, + tokenizer_path=mpt_pth, + cross_attn_every_n_layers=4) + ckpt = torch.load(ckpt_pth) + model.load_state_dict(ckpt, strict=False) + torch.cuda.empty_cache() + self.model = model.eval().cuda() + self.tokenizer = tokenizer + self.tokenizer.padding_side = 'left' + self.image_proc = image_processor + + kwargs_default = dict(max_new_tokens=512, num_beams=3) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + + def generate_inner(self, message, dataset=None): + vision_x = [] + prompt = '' + for msg in message: + if msg['type'] == 'image': + img = Image.open(msg['value']) + vision_x.append(self.image_proc(img).unsqueeze(0)) + prompt += '' + elif msg['type'] == 'text': + prompt += msg['value'] + prompt += 'Answer: ' + vision_x = torch.cat(vision_x, dim=0) if len(vision_x) > 1 else vision_x[0] + vision_x = vision_x.unsqueeze(1).unsqueeze(0) + lang_x = self.tokenizer([prompt], return_tensors='pt') + generated_text = self.model.generate( + vision_x=vision_x.cuda(), + lang_x=lang_x['input_ids'].cuda(), + attention_mask=lang_x['attention_mask'].cuda(), + **self.kwargs) + generated_text = self.tokenizer.decode(generated_text[0]) + text = generated_text[len(prompt):].split('<|endofchunk|>')[0] + return text diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/parrot.py b/VLMEvalKit-sudoku/vlmeval/vlm/parrot.py new file mode 100644 index 0000000000000000000000000000000000000000..518f00b460eec68a2f719ed089ab152e96d5ce6e --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/parrot.py @@ -0,0 +1,216 @@ +import os + +import torch +from PIL import Image +from abc import abstractproperty +from .base import BaseModel +from ..dataset import DATASET_TYPE +from ..smp import * + + +class Parrot(BaseModel): + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='AIDC-AI/Parrot-7B', **kwargs): + try: + from parrot.model.parrot_arch import ParrotMetaForCausalLM + from parrot.utils.constants import DEFAULT_IMAGE_TOKEN, BEGIN_LINE, END_LINE + from parrot.model.conversation_formatter import ConversationFormatter + from parrot.utils.mm_utils import process_images + except Exception as e: + logging.critical('Please install Parrot before using Parrot') + logging.critical('Please install Parrot from https://github.com/AIDC-AI/Parrot') + logging.critical('Using `pip install -e . --no-deps` in the Parrot directory') + logging.critical('Recommend to install transformers==4.39.0') + raise e + + self.process_images = process_images + self.ConversationFormatter = ConversationFormatter + self.DEFAULT_IMAGE_TOKEN = DEFAULT_IMAGE_TOKEN + self.BEGIN_LINE = BEGIN_LINE + self.END_LINE = END_LINE + + try: + model_name = 'parrot_qwen2' + model, tokenizer, conversation_formatter = ParrotMetaForCausalLM.build( + model_name, model_path, mm_vision_tower='openai/clip-vit-large-patch14-336' + ) + self.model = model.cuda() + self.vision_tower = self.model.get_vision_tower() + self.tokenizer = tokenizer + self.conversation_formatter = conversation_formatter + self.image_processor = self.model.get_vision_tower().image_processor + except Exception as e: + logging.critical('Error when loading Parrot model:') + raise e + + self.kwargs = dict( + do_sample=False, + num_beams=1, + max_new_tokens=512, + repetition_penalty=None, + use_cache=True, + eos_token_id=self.tokenizer.eos_token_id, + pad_token_id=self.tokenizer.pad_token_id + ) + if int(os.environ.get('LOCAL_RANK', '0')) == 0: + print(f'Following kwargs {self.kwargs} will be used as generation config.') + + self.count = 0 + + def use_custom_prompt(self, dataset): + if DATASET_TYPE(dataset) == 'Y/N' or DATASET_TYPE(dataset) == 'MCQ': + return True + return False + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + + if DATASET_TYPE(dataset) == 'Y/N': + prompt = self.built_yorn_prompt(line, dataset) + elif DATASET_TYPE(dataset) == 'MCQ': + prompt = self.build_multi_choice_prompt(line, dataset) + else: + raise ValueError(f'Invalid dataset type: {DATASET_TYPE(dataset)}') + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=p) for p in tgt_path]) + return message + + def built_yorn_prompt(self, line, dataset=None): + prompt = line['question'] + previous_suffixs = [' Please answer yes or no.', ' Yes or No', ' Answer in one sentence.'] + for previous_suffix in previous_suffixs: + if prompt.endswith(previous_suffix): + prompt = prompt[:-len(previous_suffix)] + break + prompt += '\n请直接回答Yes或No。请用单个词或短语回答问题。' if cn_string( + prompt) else '\nPlease strictly answer Yes or No. Answer the question using a single word or phrase.' + return prompt + + def build_multi_choice_prompt(self, line, dataset=None): + question = line['question'] + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + default_prompt = "\nAnswer with the option's letter from the given choices directly." + if dataset[-3:] == '_cn' or cn_string(prompt): + default_prompt = '\n请直接用给定选项中的选项字母回答。' + elif dataset[-3:] == '_pt': + default_prompt = '\nResponda diretamente com a letra da opção das escolhas dadas.' + elif dataset[-3:] == '_ar': + default_prompt = '\nأجب مباشرةً بحرف الخيار من الاختيارات المعطاة.' + elif dataset[-3:] == '_ru': + default_prompt = '\nОтветьте буквой варианта из предложенных вариантов напрямую.' + elif dataset[-3:] == '_tr': + default_prompt = '\nVerilen seçeneklerden doğrudan seçeneğin harfi ile cevap verin.' + prompt += default_prompt + # prompt += ( + # '\n请直接回答选项字母。' if cn_string(prompt) else + # "\nAnswer with the option's letter from the given choices directly." + # ) + else: + prompt += '\n请用单个词或短语回答问题。' if cn_string( + prompt) else '\nAnswer the question using a single word or phrase.' + + return prompt + + def process_answer_prefix(self, answer, prefixes): + for prefix in prefixes: + if prefix in answer.lower(): + return answer[answer.lower().find(prefix) + len(prefix):] + return answer + + def generate_inner(self, message, dataset=None): + query, image_paths = self.prepare_inputs(message) + images_list = [Image.open(image_path).convert('RGB') for image_path in image_paths] + args = abstractproperty() + args.image_aspect_ratio = 'pad' + image_tensors = self.process_images(images_list, self.image_processor, args).cuda() + prompt, input_ids = self.conversation_formatter.format_query(query) + input_ids = input_ids.unsqueeze(0).cuda() + + with torch.inference_mode(): + kwargs = dict( + images=image_tensors, + ) + kwargs.update(self.kwargs) + output_ids = self.model.generate(input_ids, **kwargs) + + input_token_len = input_ids.shape[1] + n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item() + if n_diff_input_output > 0: + print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids') + response = self.tokenizer.batch_decode(output_ids[:, input_token_len:], + skip_special_tokens=True)[0].strip(string.whitespace) + answer = response + + if query.endswith("Answer with the option's letter from the given choices directly.") or query.endswith( + '请直接回答选项字母。'): + qtype = 'multiple-choice' + while True: + answer = answer.strip(string.punctuation + string.whitespace) + if len(answer) > 1: + if answer[0] in string.ascii_uppercase and answer[1] in string.whitespace + string.punctuation: + answer = answer[0] + break + elif answer[-1] in string.ascii_uppercase and answer[-2] in string.whitespace + string.punctuation: + answer = answer[-1] + break + elif listinstr(['answer is', 'answer:'], answer.lower()): + answer = self.process_answer_prefix(answer, ['answer is', 'answer:']) + answer = self.process_answer_prefix(answer, ['option']) + else: + break + else: + break + else: + qtype = 'open' + + if self.count % 50 == 0 and int(os.environ.get('LOCAL_RANK', '0')) == 0: + print(f'\n{self.BEGIN_LINE}') + print(f'image_paths: {image_paths}\n') + print(f'prompt: {prompt}\n') + print(f'qtype: {qtype}\n') + print(f'output: {response}\n') + print(f'answer: {answer}\n') + print(f'{self.END_LINE}\n', flush=True) + + self.count += 1 + + return answer + + def prepare_inputs(self, message): + prompt = '' + image_paths = [] + image_count = 0 + text_count = 0 + pure_text = '' + for msg in message: + if msg['type'] == 'text': + text_count += 1 + prompt += msg['value'] + pure_text += msg['value'] + elif msg['type'] == 'image': + image_count += 1 + prompt += self.DEFAULT_IMAGE_TOKEN + image_paths.append(msg['value']) + + if image_count == 1 and text_count == 1: + prompt = self.DEFAULT_IMAGE_TOKEN + '\n' + pure_text + + return prompt, image_paths diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/phi4_multimodal.py b/VLMEvalKit-sudoku/vlmeval/vlm/phi4_multimodal.py new file mode 100644 index 0000000000000000000000000000000000000000..6d206f789acad63672b0f422c7fd32c2e2b864ea --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/phi4_multimodal.py @@ -0,0 +1,57 @@ +from PIL import Image +import torch + +from .base import BaseModel +from ..smp import * + + +class Phi4Multimodal(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='microsoft/Phi-4-multimodal-instruct', **kwargs): + try: + from transformers import AutoProcessor, AutoModelForCausalLM, GenerationConfig + except Exception as e: + logging.critical('Please install the latest version transformers.') + raise e + + model = AutoModelForCausalLM.from_pretrained( + model_path, device_map='cuda', trust_remote_code=True, + torch_dtype='auto',attn_implementation='flash_attention_2' + ).eval() + processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) + generation_config = GenerationConfig.from_pretrained(model_path) + + self.model = model + self.processor = processor + # self.kwargs = kwargs + self.generation_config = generation_config + + def generate_inner(self, message, dataset=None): + user_question = '\n'.join([msg['value'] for msg in message if msg['type'] == 'text']) + images = [Image.open(msg['value']).convert('RGB') for msg in message if msg['type'] == 'image'] + + user_prompt = '<|user|>' + assistant_prompt = '<|assistant|>' + prompt_suffix = '<|end|>' + prompt = f'{user_prompt}<|image_placeholder|>{user_question}{prompt_suffix}{assistant_prompt}' + image_prompt = '' + for num in range(1, len(images) + 1): + image_prompt += f'<|image_{num}|>' + prompt = prompt.replace('<|image_placeholder|>', image_prompt, 1) + + inputs = self.processor(text=prompt, images=images, return_tensors='pt').to('cuda') + + # Generate response + generate_ids = self.model.generate( + **inputs, + max_new_tokens=1000, + generation_config=self.generation_config, + ) + generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:] + response = self.processor.batch_decode( + generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False + )[0] + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/pixtral.py b/VLMEvalKit-sudoku/vlmeval/vlm/pixtral.py new file mode 100644 index 0000000000000000000000000000000000000000..8e606edcd4374666714518046d9bb2c31eaa050a --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/pixtral.py @@ -0,0 +1,70 @@ +import torch +from PIL import Image +from .base import BaseModel +from ..smp import * +import warnings +from huggingface_hub import snapshot_download + + +class Pixtral(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='mistralai/Pixtral-12B-2409', **kwargs): + + self.model_path = model_path + try: + from mistral_inference.transformer import Transformer + from mistral_common.tokens.tokenizers.mistral import MistralTokenizer + except ImportError as err: + logging.critical('Please install `mistral-inference` and `mistral_common`') + raise err + + if os.path.exists(model_path): + cache_path = model_path + else: + if get_cache_path(model_path, repo_type='models') is None: + snapshot_download(repo_id=model_path) + cache_path = get_cache_path(self.model_path, repo_type='models') + + self.tokenizer = MistralTokenizer.from_file(f'{cache_path}/tekken.json') + model = Transformer.from_folder(cache_path, device='cpu') + model.cuda() + self.model = model + self.max_tokens = 2048 + + def generate_inner(self, message, dataset=None): + try: + from mistral_inference.generate import generate + from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageURLChunk + from mistral_common.protocol.instruct.request import ChatCompletionRequest + except ImportError as err: + logging.critical('Please install `mistral-inference` and `mistral_common`') + raise err + + msg_new = [] + for msg in message: + tp, val = msg['type'], msg['value'] + if tp == 'text': + msg_new.append(TextChunk(text=val)) + elif tp == 'image': + b64 = encode_image_file_to_base64(val) + image_url = f'data:image/jpeg;base64,{b64}' + msg_new.append(ImageURLChunk(image_url=image_url)) + + completion_request = ChatCompletionRequest(messages=[UserMessage(content=msg_new)]) + encoded = self.tokenizer.encode_chat_completion(completion_request) + images = encoded.images + tokens = encoded.tokens + + out_tokens, _ = generate( + [tokens], + self.model, + images=[images], + max_tokens=self.max_tokens, + temperature=0, + eos_id=self.tokenizer.instruct_tokenizer.tokenizer.eos_id) + + result = self.tokenizer.decode(out_tokens[0]) + return result diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/qh_360vl.py b/VLMEvalKit-sudoku/vlmeval/vlm/qh_360vl.py new file mode 100644 index 0000000000000000000000000000000000000000..616495463f1aaa529e6abb7b884732e5c8d9436d --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/qh_360vl.py @@ -0,0 +1,61 @@ +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer +import warnings +import os.path as osp +from PIL import Image +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE + + +class QH_360VL(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='qihoo360/360VL-70B', **kwargs): + assert model_path is not None + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + self.model = AutoModelForCausalLM.from_pretrained(model_path, + torch_dtype=torch.float16, + low_cpu_mem_usage=True, + device_map="auto", + trust_remote_code=True).eval() + vision_tower = self.model.get_vision_tower() + vision_tower.load_model() + vision_tower.to(device='cuda', dtype=torch.float16) + self.image_processor = vision_tower.image_processor + self.tokenizer.pad_token = self.tokenizer.eos_token + self.kwargs = kwargs + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + torch.cuda.empty_cache() + + def generate(self, message, dataset=None): + + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + print(prompt) + image = Image.open(image_path).convert('RGB') + terminators = [ + self.tokenizer.convert_tokens_to_ids('<|eot_id|>',) + ] + inputs = self.model.build_conversation_input_ids(self.tokenizer, + query=prompt, + image=image, + image_processor=self.image_processor) + input_ids = inputs['input_ids'].to(device='cuda', non_blocking=True) + images = inputs['image'].to(dtype=torch.float16, device='cuda', non_blocking=True) + + output_ids = self.model.generate(input_ids=input_ids, + images=images, + do_sample=False, + num_beams=1, + max_new_tokens=512, + eos_token_id=terminators, + use_cache=True) + + input_token_len = input_ids.shape[1] + outputs = self.tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0] + response = outputs.strip() + + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/rbdash.py b/VLMEvalKit-sudoku/vlmeval/vlm/rbdash.py new file mode 100644 index 0000000000000000000000000000000000000000..564a7af8df77fb897ac93909b6026e743ded3ef2 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/rbdash.py @@ -0,0 +1,282 @@ +import sys +import torch +import os.path as osp +import os +import warnings +from .base import BaseModel +from ..dataset import DATASET_TYPE +from ..smp import * +from PIL import Image +''' + Please follow the instructions to download ckpt. + https://github.com/RBDash-Team/RBDash?tab=readme-ov-file#pretrained-weights +''' + + +class RBDash(BaseModel): + INSTALL_REQ = True + INTERLEAVE = False + + def __init__(self, model_path, root=None, conv_mode='qwen', **kwargs): + from huggingface_hub import snapshot_download + if root is None: + raise ValueError('Please set `root` to RBDash code directory, \ + which is cloned from here: "https://github.com/RBDash-Team/RBDash?tab=readme-ov-file" ') + warnings.warn('Please follow the instructions of RBDash to put the ckpt file in the right place, \ + which can be found at https://github.com/RBDash-Team/RBDash?tab=readme-ov-file#structure') + assert model_path == 'RBDash-Team/RBDash-v1.5', 'We only support RBDash-v1.5 for now' + sys.path.append(root) + try: + from rbdash.model.builder import load_pretrained_model + from rbdash.mm_utils import get_model_name_from_path + except Exception as err: + logging.critical( + 'Please first install RBdash and set the root path to use RBdash, ' + 'which is cloned from here: "https://github.com/RBDash-Team/RBDash?tab=readme-ov-file" ' + ) + raise err + + VLMEvalKit_path = os.getcwd() + os.chdir(root) + warnings.warn('Please set `root` to RBdash code directory, \ + which is cloned from here: "https://github.com/RBDash-Team/RBDash?tab=readme-ov-file" ') + try: + model_name = get_model_name_from_path(model_path) + except Exception as err: + logging.critical( + 'Please follow the instructions of RBdash to put the ckpt file in the right place, ' + 'which can be found at https://github.com/RBDash-Team/RBDash?tab=readme-ov-file#structure' + ) + raise err + + download_model_path = snapshot_download(model_path) + + internvit_local_dir = './model_zoo/OpenGVLab/InternViT-6B-448px-V1-5' + os.makedirs(internvit_local_dir, exist_ok=True) + snapshot_download('OpenGVLab/InternViT-6B-448px-V1-5', local_dir=internvit_local_dir) + + convnext_local_dir = './model_zoo/OpenAI/openclip-convnext-large-d-320-laion2B-s29B-b131K-ft-soup' + os.makedirs(convnext_local_dir, exist_ok=True) + snapshot_download('laion/CLIP-convnext_large_d_320.laion2B-s29B-b131K-ft-soup', local_dir=convnext_local_dir) + preprocessor_url = 'https://huggingface.co/openai/clip-vit-large-patch14-336/blob/main/preprocessor_config.json' + download_file_path = osp.join(convnext_local_dir, 'preprocessor_config.json') + if not osp.exists(download_file_path): + print(f'download preprocessor to {download_file_path}') + download_file(preprocessor_url, download_file_path) + + tokenizer, model, image_processor, image_processor_aux, context_len = load_pretrained_model( + download_model_path, None, model_name, device_map="auto" + ) + os.chdir(VLMEvalKit_path) + self.model = model + self.tokenizer = tokenizer + self.image_processor = image_processor + self.image_processor_aux = image_processor_aux + self.conv_mode = conv_mode + + if tokenizer.unk_token is None: + tokenizer.unk_token = '<|endoftext|>' + tokenizer.pad_token = tokenizer.unk_token + + kwargs_default = dict(temperature=float(0.2), num_beams=1, top_p=None, max_new_tokens=128, use_cache=True) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + + def generate_inner(self, message, dataset=None): + try: + from rbdash.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, \ + DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN + from rbdash.conversation import conv_templates + from rbdash.mm_utils import tokenizer_image_token, process_images + except Exception as err: + logging.critical( + 'Please first install RBdash and set the root path to use RBdash, ' + 'which is cloned from here: "https://github.com/RBDash-Team/RBDash?tab=readme-ov-file" ' + ) + raise err + + prompt, image = self.message_to_promptimg(message, dataset=dataset) + image = Image.open(image).convert('RGB') + + if self.model.config.mm_use_im_start_end: + prompt = ( + DEFAULT_IM_START_TOKEN + + DEFAULT_IMAGE_TOKEN + + DEFAULT_IM_END_TOKEN + + '\n' + + prompt + ) + else: + prompt = DEFAULT_IMAGE_TOKEN + '\n' + prompt + + conv = conv_templates[self.conv_mode].copy() + conv.append_message(conv.roles[0], prompt) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt') + input_ids = input_ids.unsqueeze(0).cuda() + if hasattr(self.model.config, 'image_size_aux'): + if not hasattr(self.image_processor, 'image_size_raw'): + self.image_processor.image_size_raw = self.image_processor.crop_size.copy() + self.image_processor.crop_size['height'] = self.model.config.image_size_aux + self.image_processor.crop_size['width'] = self.model.config.image_size_aux + self.image_processor.size['shortest_edge'] = self.model.config.image_size_aux + self.image_processor_aux.crop_size['height'] = self.model.config.image_size_aux + self.image_processor_aux.crop_size['width'] = self.model.config.image_size_aux + self.image_processor_aux.size[ + 'shortest_edge' + ] = self.model.config.image_size_aux + image_tensor = process_images([image], self.image_processor, self.model.config)[0] + image_grid = getattr(self.model.config, 'image_grid', 1) + if hasattr(self.model.config, 'image_size_aux'): + raw_shape = [ + self.image_processor.image_size_raw['height'] * image_grid, + self.image_processor.image_size_raw['width'] * image_grid + ] + if self.image_processor is not self.image_processor_aux: + image_tensor_aux = process_images([image], self.image_processor_aux, self.model.config)[ + 0 + ] + else: + image_tensor_aux = image_tensor + image_tensor = torch.nn.functional.interpolate( + image_tensor[None], + size=raw_shape, + mode='bilinear', + align_corners=False + )[0] + else: + image_tensor_aux = [] + if image_grid >= 2: + raw_image = image_tensor.reshape( + 3, image_grid, self.image_processor.image_size_raw['height'], + image_grid, self.image_processor.image_size_raw['width'] + ) + raw_image = raw_image.permute(1, 3, 0, 2, 4) + raw_image = raw_image.reshape( + -1, 3, self.image_processor.image_size_raw['height'], self.image_processor.image_size_raw['width'] + ) + + if getattr(self.model.config, 'image_global', False): + global_image = image_tensor + if len(global_image.shape) == 3: + global_image = global_image[None] + global_image = torch.nn.functional.interpolate( + global_image, + size=[ + self.image_processor.image_size_raw['height'], + self.image_processor.image_size_raw['width'] + ], + mode='bilinear', + align_corners=False + ) + raw_image = torch.cat([raw_image, global_image], dim=0) + image_tensor = raw_image.contiguous() + + images = image_tensor[None].to(dtype=self.model.dtype, device='cuda', non_blocking=True) + if len(image_tensor_aux) > 0: + images_aux = image_tensor_aux[None].to(dtype=self.model.dtype, device='cuda', non_blocking=True) + else: + images_aux = None + + with torch.inference_mode(): + output_ids = self.model.generate( + input_ids, + max_new_tokens=512, + images=images, + images_aux=images_aux, + do_sample=True if self.kwargs['temperature'] > 0 else False, + temperature=self.kwargs['temperature'], + top_p=self.kwargs['top_p'], + num_beams=self.kwargs['num_beams'] + ) + + outputs = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() + return outputs + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(['MMDU', 'MME-RealWorld', 'MME-RealWorld-CN'], dataset): + # For Multi-Turn we don't have custom prompt + return False + if 'mme' in dataset.lower(): + return True + elif 'hallusionbench' in dataset.lower(): + return True + elif 'mmmu' in dataset.lower(): + return True + elif 'mmbench' in dataset.lower(): + return True + return False + + def build_mme(self, line): + question = line['question'] + prompt = question + 'Answer the question using a single word or phrase.' + return prompt + + def build_hallusionbench(self, line): + question = line['question'] + prompt = question + '\nAnswer the question using a single word or phrase.' + return prompt + + def build_mmbench(self, line): + question = line['question'] + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = 'Options:\n' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = '' + if hint is not None: + prompt += f'Hint: {hint}\n' + prompt += f'Question: {question}\n' + if len(options): + prompt += options_prompt + prompt += "Answer with the option's letter from the given choices directly." + else: + prompt += 'Answer the question using a single word or phrase.' + return prompt + + def build_mmmu(self, line): + question = line['question'] + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = 'Options:\n' + for key, item in options.items(): + options_prompt += f'({key}) {item}\n' + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + prompt = '' + if hint is not None: + prompt += f'Hint: {hint}\n' + prompt += f'Question: {question}\n' + if len(options): + prompt += options_prompt + prompt += "Answer with the option's letter from the given choices directly." + else: + prompt += 'Answer the question using a single word or phrase.' + return prompt + + def build_prompt(self, line, dataset=None): + assert dataset is None or isinstance(dataset, str) + assert self.use_custom_prompt(dataset) + tgt_path = self.dump_image(line, dataset) + if 'mme' in dataset.lower(): + prompt = self.build_mme(line) + elif 'hallusionbench' in dataset.lower(): + prompt = self.build_hallusionbench(line) + elif 'mmmu' in dataset.lower(): + prompt = self.build_mmmu(line) + elif 'mmbench' in dataset.lower(): + prompt = self.build_mmbench(line) + + ret = [dict(type='text', value=prompt)] + ret.extend([dict(type='image', value=s) for s in tgt_path]) + return ret diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/ristretto.py b/VLMEvalKit-sudoku/vlmeval/vlm/ristretto.py new file mode 100644 index 0000000000000000000000000000000000000000..ba53000ad0844ae40dc98270d6b778c7d3243ab3 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/ristretto.py @@ -0,0 +1,397 @@ +import torch +from transformers import AutoTokenizer, AutoConfig, AutoModel +import warnings +from PIL import Image +from .base import BaseModel +from ..smp import * +from ..dataset import DATASET_TYPE, DATASET_MODALITY +import pandas as pd +import string +import torch.distributed as dist +import torchvision.transforms as T +import transformers + +from torchvision.transforms.functional import InterpolationMode +import re + +from transformers.utils import logging +logger = logging.get_logger(__name__) + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + +CLIP_MEAN = (0.4814546, 0.4578275, 0.40821073) +CLIP_STD = (0.2686295, 0.2613025, 0.2757711) +SIGLIP_MEAN = (0.5, 0.5, 0.5) +SIGLIP_STD = (0.5, 0.5, 0.5) + + +def build_transform(input_size, normalize_type='imagenet'): + if normalize_type == 'imagenet': + MEAN, STD = IMAGENET_MEAN, IMAGENET_STD + elif normalize_type == 'clip': + MEAN, STD = CLIP_MEAN, CLIP_STD + elif normalize_type == 'siglip': + MEAN, STD = SIGLIP_MEAN, SIGLIP_STD + else: + raise NotImplementedError + transform = T.Compose([ + T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), + T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(mean=MEAN, std=STD) + ]) + return transform + + +def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): + best_ratio_diff = float('inf') + best_ratio = (1, 1) + area = width * height + for ratio in target_ratios: + target_aspect_ratio = ratio[0] / ratio[1] + ratio_diff = abs(aspect_ratio - target_aspect_ratio) + if ratio_diff < best_ratio_diff: + best_ratio_diff = ratio_diff + best_ratio = ratio + elif ratio_diff == best_ratio_diff: + if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: + best_ratio = ratio + return best_ratio + + +def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if + i * j <= max_num and i * j >= min_num) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio( + aspect_ratio, target_ratios, orig_width, orig_height, image_size) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images + + +def load_image(image_file, input_size=448, max_num=6, upscale=False, normalize_type="imagenet"): + image = Image.open(image_file).convert('RGB') + if upscale: + image = image.resize((image.width * 2, image.height * 2), Image.BILINEAR) + transform = build_transform(input_size=input_size, normalize_type=normalize_type) + images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values + + +def extract_answer(text): + match = re.search(r'(Final answer:|Answer:)\s*(.*)', text, re.IGNORECASE) + if match: + return match.group(2).strip() + return text + + +class Ristretto(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, + model_path='', + load_in_8bit=False, + cot_prompt=False, + **kwargs): + + assert model_path is not None + assert version_cmp(transformers.__version__, '4.36.2', 'ge') + + self.cot_prompt = cot_prompt + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False) + self.config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) + if self.config.vision_config.model_type == "siglip_vision_model": + self.normalize_type = "siglip" + else: + self.normalize_type = "imagenet" + self.image_size = self.config.vision_config.image_size + + # Regular expression to match the pattern 'Image' followed by a number, e.g. Image1 + self.pattern = r'Image(\d+)' + # Replacement pattern to insert a hyphen between 'Image' and the number, e.g. Image-1 + self.replacement = r'Image-\1' + + # Regular expression to match the pattern 'Image-' followed by a number + self.reverse_pattern = r'Image-(\d+)' + # Replacement pattern to remove the hyphen (Image-1 -> Image1) + self.reverse_replacement = r'Image\1' + self.device = 'cuda' + + self.model = AutoModel.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + load_in_8bit=load_in_8bit, + trust_remote_code=True).eval() + if not load_in_8bit: + self.model = self.model.to('cuda') + self.model = self.model.to(torch.bfloat16) + self.image_size = self.model.config.vision_config.image_size + kwargs_default = dict(do_sample=False, max_new_tokens=1024, top_p=None, num_beams=1) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(['MMDU', 'MME-RealWorld', 'MME-RealWorld-CN'], dataset): + # For Multi-Turn we don't have custom prompt + return False + if DATASET_MODALITY(dataset) == 'VIDEO': + # For Video benchmarks we don't have custom prompt at here + return False + else: + return True + + def build_multi_choice_prompt(self, line, dataset=None): + question = line['question'] + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + prompt += '\n请直接回答选项字母。' if cn_string( + prompt) else "\nAnswer with the option's letter from the given choices directly." + else: + prompt += '\n请直接回答问题。' if cn_string(prompt) else '\nAnswer the question directly.' + + return prompt + + def build_video_prompt(self, prompt, dataset=None, max_frames=64): + for start in range(0, max_frames, 8): + images_to_remove = ''.join([f'' for i in range(start + 1, start + 9)]) + prompt = prompt.replace(images_to_remove, '') + for i in range(max_frames): + prompt = prompt.replace(f'Image-{i + 1}', f'Frame-{i + 1}') + if listinstr(['MMBench-Video'], dataset): + prompt = prompt.replace('\nAnswer:', '') + elif listinstr(['Video-MME'], dataset): + prompt = prompt.replace('\nAnswer:', '') + prompt += "\nAnswer with the option's letter from the given choices directly." + elif listinstr(['MVBench'], dataset): + prompt = prompt.replace('Best option:(', '') + + return prompt + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + + kwargs_default = dict(do_sample=False, max_new_tokens=1024, top_p=None, num_beams=1) + if int(os.environ.get("MAX_NEW_TOKENS", 0)) != 0: + kwargs_default["max_new_tokens"] = int(os.environ.get("MAX_NEW_TOKENS", 0)) + self.kwargs = kwargs_default + + if dataset is not None and DATASET_TYPE(dataset) == 'Y/N': + question = line['question'] + if listinstr(['MME'], dataset): + prompt = question + ' Answer the question using a single word or phrase.' + elif listinstr(['HallusionBench'], dataset): + prompt = question + ' Please answer yes or no. Answer the question using a single word or phrase.' + else: + prompt = question + elif dataset is not None and DATASET_TYPE(dataset) == 'MCQ': + prompt = self.build_multi_choice_prompt(line, dataset) + elif dataset is not None and DATASET_TYPE(dataset) == 'VQA': + question = line['question'] + if listinstr(['MathVista', 'MathVision', 'VCR', 'MTVQA', 'MMVet', 'MathVerse'], dataset): + prompt = question + elif listinstr(['LLaVABench'], dataset): + prompt = question + '\nAnswer this question in detail.' + else: + prompt = question + '\nAnswer the question using a single word or phrase.' + else: + prompt = line['question'] + + if self.cot_prompt and not listinstr(['LLaVABench'], dataset): + cot_prompt_with_final_answer = ( + "Your task is to answer the question below. " + "Give step by step reasoning before you answer, and when you're ready to answer, " + "please use the format \"Final answer: ..\"" + "\n\n" + "Question:" + "\n\n" + "{question}" + ) + cot_prompt_wo_final_answer = ( + "Your task is to answer the question below. " + "Give step by step reasoning. " + "\n\n" + "Question:" + "\n\n" + "{question}" + ) + + if listinstr(['MMVet'], dataset): + cot_prompt = cot_prompt_wo_final_answer + else: + cot_prompt = cot_prompt_with_final_answer + + question_orig = line['question'] + if listinstr(['MathVerse', 'MathVision'], dataset): + question_orig = question_orig.split('Question:', 1)[-1].strip() + question_orig = question_orig.replace('Choices:\n', '').strip() + + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + options_prompt = '' + for key, item in options.items(): + options_prompt += f'{key}. {item}\n' + + if options_prompt.strip(): + question_orig = f'{question_orig}\n{options_prompt}' + + prompt = cot_prompt.format(question=question_orig) + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=s) for s in tgt_path]) + return message + + def set_max_num(self, dataset): + if int(os.environ.get("MAX_PATCH_NUM", 0)) != 0: + max_patch_num = int(os.environ.get("MAX_PATCH_NUM", None)) + self.max_num = max_patch_num + return None + + if dataset is None: + self.max_num = 6 + return None + # res_1_datasets = ['MMBench-Video', 'Video-MME', 'MVBench', 'Video'] + res_12_datasets = ['ChartQA_TEST', 'MMMU_DEV_VAL', 'MMMU_TEST', 'MME-RealWorld', + 'MME-RealWorld', 'VCR_EN', 'VCR_ZH'] + res_18_datasets = ['DocVQA_VAL', 'DocVQA_TEST'] + res_24_datasets = ['InfoVQA_VAL', 'InfoVQA_TEST', 'OCRBench', 'HRBench4K', 'HRBench8K'] + if DATASET_MODALITY(dataset) == 'VIDEO': + self.max_num = 1 + elif listinstr(res_12_datasets, dataset): + self.max_num = 12 + elif listinstr(res_18_datasets, dataset): + self.max_num = 18 + elif listinstr(res_24_datasets, dataset): + self.max_num = 24 + else: + self.max_num = 6 + + def _generate(self, message, dataset=None): + image_num = len([x for x in message if x['type'] == 'image']) + if image_num == 1: + prompt = '\n' + '\n'.join([x['value'] for x in message if x['type'] == 'text']) + else: + prompt, image_idx = '', 1 + for x in message: + if x['type'] == 'text': + prompt += x['value'] + elif x['type'] == 'image': + prompt += f'' + image_idx += 1 + prompt = '\n'.join([f'Image-{i + 1}: ' for i in range(image_num)]) + '\n' + prompt + + if dataset is not None and DATASET_MODALITY(dataset) == 'VIDEO': + prompt = self.build_video_prompt(prompt, dataset) + + if image_num > 1: + image_path = [x['value'] for x in message if x['type'] == 'image'] + num_patches_list = [] + pixel_values_list = [] + for image_idx, file_name in enumerate(image_path): + upscale_flag = image_idx == 0 and dataset is not None and listinstr(['MMMU_DEV_VAL'], dataset) + curr_pixel_values = load_image( + file_name, input_size=self.image_size, max_num=self.max_num, + upscale=upscale_flag, normalize_type=self.normalize_type + ).to(self.device).to(torch.bfloat16) + num_patches_list.append(curr_pixel_values.size(0)) + pixel_values_list.append(curr_pixel_values) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_num == 1: + image_path = [x['value'] for x in message if x['type'] == 'image'][0] + upscale_flag = dataset is not None and listinstr(['MMMU_DEV_VAL'], dataset) + pixel_values = load_image( + image_path, input_size=self.image_size, max_num=self.max_num, + upscale=upscale_flag, normalize_type=self.normalize_type + ).to(self.device).to(torch.bfloat16) + num_patches_list = [pixel_values.size(0)] + else: + pixel_values = None + num_patches_list = [] + + num_image_token = 256 + if dataset is not None: + if listinstr(['MMBench_DEV_EN_V11', 'MathVista_MINI', 'MMVet'], dataset): + num_image_token = 144 + elif listinstr(['HallusionBench'], dataset): + num_image_token = 576 + + with torch.no_grad(): + response = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + num_patches_list=num_patches_list, + question=prompt, + num_image_token=num_image_token, + generation_config=self.kwargs, + verbose=False + ) + + if ( + self.cot_prompt + and dataset is not None + and ( + DATASET_TYPE(dataset) in ['Y/N', 'MCQ'] + or listinstr(['CRPE'], dataset) + ) + ): + response = extract_answer(response).strip() + + return response + + def generate_inner(self, message, dataset=None): + self.set_max_num(dataset) + return self._generate(message, dataset) diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/sail_vl.py b/VLMEvalKit-sudoku/vlmeval/vlm/sail_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..8375d01330b8bb2d2f6d6895937272a9dfaafcb2 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/sail_vl.py @@ -0,0 +1,658 @@ +import math +import pandas as pd +import random +import re +import string +import torch +import torch.distributed as dist +import torchvision.transforms as T +import transformers +import warnings +from PIL import Image +from torchvision.transforms.functional import InterpolationMode +from transformers import AutoTokenizer, AutoConfig, AutoModel, CLIPImageProcessor + +from .base import BaseModel +from ..dataset import DATASET_TYPE, DATASET_MODALITY +from ..smp import * + + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) + + +def build_transform(input_size): + MEAN, STD = IMAGENET_MEAN, IMAGENET_STD + transform = T.Compose( + [ + T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img), + T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), + T.ToTensor(), + T.Normalize(mean=MEAN, std=STD), + ] + ) + return transform + + +def get_cot_answer(response): + pattern1 = r"(?P.*?).*?\\boxed\{(?P[^{}]*(?:\{[^{}]*\}[^{}]*)*)\}" + match = re.search(pattern1, response, re.DOTALL) + if match: + return match.group("answer") + pattern2 = r"\\boxed\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}" + matches = re.findall(pattern2, response, re.DOTALL) + if matches: + return matches[-1] + return response + + +def process_response(response, dataset_name, use_cot=False): + if use_cot: + response = get_cot_answer(response) + if dataset_name is None: + return response + if listinstr(["ChartQA", "OCRVQA"], dataset_name): + if len(response) >= 1 and response[-1] == ".": + response = response[:-1] + return response + + +def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): + best_ratio_diff = float("inf") + best_ratio = (1, 1) + area = width * height + for ratio in target_ratios: + target_aspect_ratio = ratio[0] / ratio[1] + ratio_diff = abs(aspect_ratio - target_aspect_ratio) + if ratio_diff < best_ratio_diff: + best_ratio_diff = ratio_diff + best_ratio = ratio + elif ratio_diff == best_ratio_diff: + if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: + best_ratio = ratio + return best_ratio + + +def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) + for n in range(min_num, max_num + 1) + for i in range(1, n + 1) + for j in range(1, n + 1) + if i * j <= max_num and i * j >= min_num + ) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size, + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images + + +def load_image(image_file, input_size=448, max_num=6, upscale=False): + image = Image.open(image_file).convert("RGB") + if upscale: + image = image.resize((image.width * 2, image.height * 2), Image.BILINEAR) + transform = build_transform(input_size=input_size) + images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values + + +def get_local_rank_and_local_world_size(): + if not dist.is_available(): + return 0, 1 + if not dist.is_initialized(): + return 0, 1 + + if "SLURM_LOCALID" in os.environ: + local_rank = int(os.environ["SLURM_LOCALID"]) + local_world_size = int(os.environ["SLURM_NTASKS_PER_NODE"]) + return local_rank, local_world_size + + if "LOCAL_RANK" in os.environ and "LOCAL_WORLD_SIZE" in os.environ: + return int(os.environ["LOCAL_RANK"]), int(os.environ["LOCAL_WORLD_SIZE"]) + + raise NotImplementedError( + "Fail to get local_rank and local_world_size! " + "Please ensure that you set the environment variable " + "`LOCAL_RANK` and `LOCAL_WORLD_SIZE`" + ) + + +def build_multi_choice_prompt(line, dataset=None): + question = line["question"] + hint = line["hint"] if ("hint" in line and not pd.isna(line["hint"])) else None + if hint is not None: + question = hint + "\n" + question + + options = {cand: line[cand] for cand in string.ascii_uppercase if cand in line and not pd.isna(line[cand])} + for key, item in options.items(): + question += f"\n{key}. {item}" + prompt = question + + if len(options): + prompt += ( + "\n请直接回答选项字母。" + if cn_string(prompt) + else "\nAnswer with the option's letter from the given choices directly." + ) + else: + prompt += "\n请直接回答问题。" if cn_string(prompt) else "\nAnswer the question directly." + + return prompt + + +def build_video_prompt(prompt, dataset=None, max_frames=64): + for start in range(0, max_frames, 8): + images_to_remove = "".join([f"" for i in range(start + 1, start + 9)]) + prompt = prompt.replace(images_to_remove, "") + for i in range(max_frames): + prompt = prompt.replace(f"Image-{i + 1}", f"Frame-{i + 1}") + if listinstr(["MMBench-Video"], dataset): + prompt = prompt.replace("\nAnswer:", "") + elif listinstr(["Video-MME"], dataset): + prompt = prompt.replace("\nAnswer:", "") + prompt += "\nAnswer with the option's letter from the given choices directly." + elif listinstr(["MVBench"], dataset): + prompt = prompt.replace("Best option:(", "") + + return prompt + + +def reorganize_prompt(message, image_num, dataset=None): + if dataset is not None and listinstr(["MUIRBench"], dataset): + prompt = "\n".join([x["value"] for x in message if x["type"] == "text"]) + images_to_remove = " ".join([""] * image_num) + prompt = prompt.replace(images_to_remove, "") + for i in range(image_num): + prompt = prompt.replace("", f"", 1) + prompt = "".join([f"Image-{i + 1}: \n" for i in range(image_num)]) + prompt + elif dataset is not None and listinstr(["bmmr"], dataset.lower()): + if image_num == 1: + prompt = "\n".join([x["value"] for x in message if x["type"] == "text"]) + else: + prompt, image_idx = "", 1 + for x in message: + if x["type"] == "text": + prompt += x["value"] + elif x["type"] == "image": + image_idx += 1 + elif image_num == 1: + prompt = "\n" + "\n".join([x["value"] for x in message if x["type"] == "text"]) + else: + prompt, image_idx = "", 1 + for x in message: + if x["type"] == "text": + prompt += x["value"] + elif x["type"] == "image": + prompt += f"" + image_idx += 1 + prompt = "".join([f"Image-{i + 1}: \n" for i in range(image_num)]) + prompt + images_to_remove = "".join([f"" for i in range(image_num)]) + prompt = prompt.replace(images_to_remove, "") + return prompt + + +def dynamic_preprocess_msac1(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) + for n in range(min_num, max_num + 1) + for i in range(1, n + 1) + for j in range(1, n + 1) + if i * j <= max_num and i * j >= min_num + ) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size, + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images, target_aspect_ratio + + +def dynamic_preprocess_msac2( + image, + min_num=1, + max_num=6, + image_size=448, + use_thumbnail=False, + prior_aspect_ratio=None, +): + orig_width, orig_height = image.size + aspect_ratio = orig_width / orig_height + + # calculate the existing image aspect ratio + target_ratios = set( + (i, j) + for n in range(min_num, max_num + 1) + for i in range(1, n + 1) + for j in range(1, n + 1) + if i * j <= max_num and i * j >= min_num + ) + target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1]) + + new_target_ratios = [] + if prior_aspect_ratio is not None: + for i in target_ratios: + if prior_aspect_ratio[0] % i[0] != 0 or prior_aspect_ratio[1] % i[1] != 0: + new_target_ratios.append(i) + else: + continue + + # find the closest aspect ratio to the target + target_aspect_ratio = find_closest_aspect_ratio( + aspect_ratio, new_target_ratios, orig_width, orig_height, image_size + ) + + # calculate the target width and height + target_width = image_size * target_aspect_ratio[0] + target_height = image_size * target_aspect_ratio[1] + blocks = target_aspect_ratio[0] * target_aspect_ratio[1] + + # resize the image + resized_img = image.resize((target_width, target_height)) + processed_images = [] + for i in range(blocks): + box = ( + (i % (target_width // image_size)) * image_size, + (i // (target_width // image_size)) * image_size, + ((i % (target_width // image_size)) + 1) * image_size, + ((i // (target_width // image_size)) + 1) * image_size, + ) + # split the image + split_img = resized_img.crop(box) + processed_images.append(split_img) + assert len(processed_images) == blocks + if use_thumbnail and len(processed_images) != 1: + thumbnail_img = image.resize((image_size, image_size)) + processed_images.append(thumbnail_img) + return processed_images + + +def load_image_msac(image_file, input_size=448, max_num=10, upscale=False): + image = Image.open(image_file).convert("RGB") + if upscale: + image = image.resize((image.width * 2, image.height * 2), Image.BILINEAR) + transform = build_transform(input_size=input_size) + images, target_aspect_ratio = dynamic_preprocess_msac1( + image, image_size=input_size, use_thumbnail=True, max_num=max_num + ) + images = ( + images[:-1] + + dynamic_preprocess_msac2( + image, + max_num=max_num, + image_size=input_size, + use_thumbnail=False, + prior_aspect_ratio=target_aspect_ratio, + ) + + images[-1:] + ) + + pixel_values = [transform(image) for image in images] + pixel_values = torch.stack(pixel_values) + return pixel_values + + +class SailVL(BaseModel): + INSTALL_REQ = False + INTERLEAVE = True + + def __init__( + self, + model_path="BytedanceDouyinContent/SAIL-VL-2B", + load_in_8bit=False, + use_msac=True, + use_cot=False, + max_new_tokens=1024, + **kwargs, + ): + assert model_path is not None + assert version_cmp(transformers.__version__, "4.36.2", "ge") + self.model_path = model_path + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False) + self.use_msac = use_msac + # Regular expression to match the pattern 'Image' followed by a number, e.g. Image1 + self.pattern = r"Image(\d+)" + # Replacement pattern to insert a hyphen between 'Image' and the number, e.g. Image-1 + self.replacement = r"Image-\1" + self.use_cot = use_cot + self.cot_prompt = ( + "You FIRST think about the reasoning process as an internal monologue " + "and then provide the final answer. The reasoning process MUST BE " + "enclosed within tags. The final answer MUST BE put in \\boxed{}." + ) + # Convert InternVL2 response to dataset format + # e.g. Image1 -> Image-1 + + # Regular expression to match the pattern 'Image-' followed by a number + self.reverse_pattern = r"Image-(\d+)" + # Replacement pattern to remove the hyphen (Image-1 -> Image1) + self.reverse_replacement = r"Image\1" + + self.model = ( + AutoModel.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + load_in_8bit=load_in_8bit, + trust_remote_code=True, + low_cpu_mem_usage=True, + ) + .eval() + .cuda() + ) + self.device = "cuda" + + self.image_size = self.model.config.vision_config.image_size + kwargs_default = dict(do_sample=False, max_new_tokens=max_new_tokens, top_p=None) + kwargs_default.update(kwargs) + self.kwargs = kwargs_default + + warnings.warn(f"Following kwargs received: {self.kwargs}, will use as generation config. ") + + def use_custom_prompt(self, dataset): + assert dataset is not None + if listinstr(["MMDU", "MME-RealWorld", "MME-RealWorld-CN"], dataset): + # For Multi-Turn we don't have custom prompt + return False + if DATASET_MODALITY(dataset) == "VIDEO": + # For Video benchmarks we don't have custom prompt at here + return False + else: + return True + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + + if dataset is not None and DATASET_TYPE(dataset) == "Y/N": + question = line["question"] + if listinstr(["MME"], dataset): + prompt = question + " Answer the question using a single word or phrase." + elif listinstr(["HallusionBench", "AMBER"], dataset): + prompt = question + " Please answer yes or no. Answer the question using a single word or phrase." + else: + prompt = question + elif dataset is not None and DATASET_TYPE(dataset) == "MCQ": + prompt = build_multi_choice_prompt(line, dataset) + elif dataset is not None and DATASET_TYPE(dataset) == "VQA": + question = line["question"] + if listinstr(["LLaVABench", "WildVision"], dataset): + prompt = question + "\nAnswer this question in detail." + elif listinstr( + [ + "OCRVQA", + "TextVQA", + "ChartQA", + "DocVQA", + "InfoVQA", + "OCRBench", + "DUDE", + "SLIDEVQA", + "GQA", + "MMLongBench_DOC", + ], + dataset, + ): + prompt = question + "\nAnswer the question using a single word or phrase." + elif listinstr( + [ + "MathVista", + "MathVision", + "VCR", + "MMVet", + "MTVQA", + "MathVerse", + "MMDU", + "CRPE", + "MIA-Bench", + "MM-Math", + "DynaMath", + "QSpatial", + ], + dataset, + ): + prompt = question + else: + prompt = question + "\nAnswer the question using a single word or phrase." + else: + # VQA_ex_prompt: OlympiadBench, VizWiz + prompt = line["question"] + message = [dict(type="text", value=prompt)] + message.extend([dict(type="image", value=s) for s in tgt_path]) + return message + + def set_max_num(self, dataset): + # The total limit on the number of images processed, set to avoid Out-of-Memory issues. + self.total_max_num = 64 + if dataset is None: + self.max_num = 10 + return None + res_12_datasets = [ + "ChartQA_TEST", + "MMMU_DEV_VAL", + "MMMU_TEST", + "MME-RealWorld", + "VCR_EN", + "VCR_ZH", + "OCRVQA", + ] + res_18_datasets = [ + "DocVQA_VAL", + "DocVQA_TEST", + "DUDE", + "MMLongBench_DOC", + "SLIDEVQA", + ] + res_24_datasets = [ + "InfoVQA_VAL", + "InfoVQA_TEST", + "OCRBench", + "HRBench4K", + "HRBench8K", + ] + if DATASET_MODALITY(dataset) == "VIDEO": + self.max_num = 1 + elif listinstr(res_12_datasets, dataset): + self.max_num = 12 + elif listinstr(res_18_datasets, dataset): + self.max_num = 18 + elif listinstr(res_24_datasets, dataset): + self.max_num = 24 + else: + self.max_num = 10 + + def generate_inner(self, message, dataset=None): + self.set_max_num(dataset) + image_num = len([x for x in message if x["type"] == "image"]) + max_num = max(1, min(self.max_num, self.total_max_num // image_num)) + prompt = reorganize_prompt(message, image_num, dataset=dataset) + + if dataset is not None and DATASET_MODALITY(dataset) == "VIDEO": + prompt = build_video_prompt(prompt, dataset) + + if image_num > 1: + image_path = [x["value"] for x in message if x["type"] == "image"] + num_patches_list, pixel_values_list = [], [] + for image_idx, file_name in enumerate(image_path): + upscale_flag = image_idx == 0 and dataset is not None and listinstr(["MMMU"], dataset) + curr_pixel_values = ( + load_image(file_name, max_num=max_num, upscale=upscale_flag).to(self.device).to(torch.bfloat16) + ) + num_patches_list.append(curr_pixel_values.size(0)) + pixel_values_list.append(curr_pixel_values) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_num == 1: + image_path = [x["value"] for x in message if x["type"] == "image"][0] + upscale_flag = dataset is not None and listinstr(["MMMU"], dataset) + if self.use_msac: + pixel_values = ( + load_image_msac( + image_path, + max_num=self.max_num, + upscale=upscale_flag, + input_size=self.image_size, + ) + .cuda() + .to(torch.bfloat16) + ) + else: + pixel_values = ( + load_image(image_path, max_num=max_num, upscale=upscale_flag).to(self.device).to(torch.bfloat16) + ) + num_patches_list = [pixel_values.size(0)] + else: + pixel_values = None + num_patches_list = [] + if self.use_cot: + prompt += f"\n{self.cot_prompt}" + with torch.no_grad(): + response = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + num_patches_list=num_patches_list, + question=prompt, + generation_config=self.kwargs, + verbose=True, + ) + response = process_response(response, dataset_name=dataset, use_cot=self.use_cot) + return response + + def build_history(self, message): + # Global Variables + image_path = [] + image_cnt = 0 + + def concat_tilist(tilist): + nonlocal image_cnt # Declare image_cnt as nonlocal to modify it + prompt = "" + for item in tilist: + # Substitute the pattern in the text + if item["type"] == "text": + prompt += re.sub(self.pattern, self.replacement, item["value"]) + elif item["type"] == "image": + image_cnt += 1 + prompt += "\n" + image_path.append(item["value"]) + return prompt + + # Only previous messages + assert len(message) % 2 == 0 + history = [] + for i in range(len(message) // 2): + m1, m2 = message[2 * i], message[2 * i + 1] + assert m1["role"] == "user" and m2["role"] == "assistant" + history.append((concat_tilist(m1["content"]), concat_tilist(m2["content"]))) + + return history, image_path, image_cnt + + def chat_inner(self, message, dataset=None): + self.set_max_num(dataset) + kwargs_default = dict(do_sample=False, max_new_tokens=512, top_p=None, num_beams=1) + self.kwargs = kwargs_default + if len(message) > 1: + history, image_path, image_cnt = self.build_history(message[:-1]) + else: + history, image_path, image_cnt = None, [], 1 + current_msg = message[-1] + question = "" + + # If message is just text in the conversation + if len(current_msg["content"]) == 1 and current_msg["content"][0]["type"] == "text": + question = current_msg["content"][0]["value"] + question = re.sub(self.pattern, self.replacement, question) # Fix pattern as per InternVL + else: + for msg in current_msg["content"]: + if msg["type"] == "text": + question += re.sub(self.pattern, self.replacement, msg["value"]) + elif msg["type"] == "image": + image_cnt += 1 + question += "\n" + image_path.append(msg["value"]) + + if image_cnt > 1: + num_patches_list = [] + pixel_values_list = [] + for image_idx, file_name in enumerate(image_path): + upscale_flag = image_idx == 0 and dataset is not None and listinstr(["MMMU_DEV_VAL"], dataset) + curr_pixel_values = ( + load_image(file_name, max_num=self.max_num, upscale=upscale_flag).to(self.device).to(torch.bfloat16) + ) + num_patches_list.append(curr_pixel_values.size(0)) + pixel_values_list.append(curr_pixel_values) + pixel_values = torch.cat(pixel_values_list, dim=0) + elif image_cnt == 1: + upscale_flag = listinstr(["MMMU_DEV_VAL"], dataset) + pixel_values = ( + load_image(image_path, max_num=self.max_num, upscale=upscale_flag).to(self.device).to(torch.bfloat16) + ) + num_patches_list = [pixel_values.size(0)] + else: + pixel_values = None + num_patches_list = [] + + response, history = self.model.chat( + self.tokenizer, + pixel_values=pixel_values, + num_patches_list=num_patches_list, + question=question, + generation_config=self.kwargs, + history=history, + return_history=True, + ) + response = re.sub(self.reverse_pattern, self.reverse_replacement, response) + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/visualglm.py b/VLMEvalKit-sudoku/vlmeval/vlm/visualglm.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f0734b899504c35362b1ddc1d9bb1c61cda03b --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/visualglm.py @@ -0,0 +1,38 @@ +import warnings +from .base import BaseModel +from ..smp import * + + +class VisualGLM(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = False + + def __init__(self, model_path='THUDM/visualglm-6b', **kwargs): + try: + import sat + except Exception as err: + logging.critical('Please install SwissArmyTransformer to use VisualGLM') + raise err + + assert model_path is not None + self.model_path = model_path + + from transformers import AutoModel + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().cuda() + self.model = model + self.kwargs = kwargs + warnings.warn(f'Following kwargs received: {self.kwargs}, will use as generation config. ') + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + output, _ = self.model.chat( + image_path=image_path, + tokenizer=self.tokenizer, + query=prompt, + history=[], + **self.kwargs + ) + return output diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/vlaa_thinker.py b/VLMEvalKit-sudoku/vlmeval/vlm/vlaa_thinker.py new file mode 100644 index 0000000000000000000000000000000000000000..01a2834c08bb9278eb4b53599662027b2152caca --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/vlaa_thinker.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import os +import torch +import re +import math +import logging +import warnings + +from .base import BaseModel +from .qwen2_vl.prompt import Qwen2VLPromptMixin +from .qwen2_vl.model import ensure_image_url, ensure_video_url +from ..smp import get_gpu_memory, listinstr + + +def extract_answer_tag(s: str, verbose=False) -> str: + # Regular expression to match content between and + matches = re.findall(r'(.*?)', s, re.DOTALL) + if len(matches) == 0: + if verbose: + print("No ... blocks found.") + return None + elif len(matches) > 1: + if verbose: + print("Multiple ... blocks found.") + return None + else: + return matches[0].strip() + + +def extract_response_for_eval(s: str, verbose=False): + ret = None + # {} + if ret is None: + ret = extract_answer_tag(s, verbose=verbose) + # + elif '' in s: + ret = s.split('')[-1] + if ret is None: + ret = s + return ret + + +class VLAAThinkerChat(Qwen2VLPromptMixin, BaseModel): + INSTALL_REQ = False + INTERLEAVE = True + VIDEO_LLM = True + + def __init__( + self, + model_path: str, + min_pixels: int | None = None, + max_pixels: int | None = None, + max_new_tokens=2048, + top_p=0.001, + top_k=1, + temperature=0.01, + repetition_penalty=1.0, + use_custom_prompt: bool = True, + system_prompt: str | None = None, + post_process: bool = False, # if True, will try to only extract stuff in the last \boxed{}. + verbose: bool = False, + **kwargs, + ): + super().__init__(use_custom_prompt=use_custom_prompt) + self.min_pixels = min_pixels + self.max_pixels = max_pixels + self.generate_kwargs = dict( + max_new_tokens=max_new_tokens, + top_p=top_p, + top_k=top_k, + temperature=temperature, + repetition_penalty=repetition_penalty, + ) + self.generate_kwargs.update(kwargs) + self.system_prompt = system_prompt + self.verbose = verbose + self.post_process = post_process + self.fps = 2.0 + self.nframe = 64 + self.FRAME_FACTOR = 2 + assert model_path is not None + self.model_path = model_path + MODEL_CLS = None + + if listinstr(['2.5', '2_5', 'qwen25'], model_path.lower()): + from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor + MODEL_CLS = Qwen2_5_VLForConditionalGeneration + self.processor = AutoProcessor.from_pretrained(model_path) + else: + from transformers import Qwen2VLForConditionalGeneration, Qwen2VLProcessor + MODEL_CLS = Qwen2VLForConditionalGeneration + self.processor = Qwen2VLProcessor.from_pretrained(model_path) + + gpu_mems = get_gpu_memory() + max_gpu_mem = max(gpu_mems) if gpu_mems != [] else -1 + assert max_gpu_mem > 0 + + self.model = MODEL_CLS.from_pretrained( + model_path, torch_dtype='auto', device_map='cuda', attn_implementation='flash_attention_2' + ) + self.model.eval() + torch.cuda.empty_cache() + + def _prepare_content(self, inputs: list[dict[str, str]], dataset: str | None = None) -> list[dict[str, str]]: + """ + inputs list[dict[str, str]], each dict has keys: ['type', 'value'] + """ + content = [] + for s in inputs: + if s['type'] == 'image': + item = {'type': 'image', 'image': ensure_image_url(s['value'])} + if dataset == 'OCRBench': + item['min_pixels'] = 10 * 10 * 28 * 28 + warnings.warn(f"OCRBench dataset uses custom min_pixels={item['min_pixels']}") + if self.max_pixels is not None: + item['max_pixels'] = self.max_pixels + else: + if self.min_pixels is not None: + item['min_pixels'] = self.min_pixels + if self.max_pixels is not None: + item['max_pixels'] = self.max_pixels + elif s['type'] == 'video': + item = {'type': 'video', 'video': ensure_video_url(s['value'])} + if self.fps is not None: + item['fps'] = self.fps + elif self.nframe is not None: + import cv2 + video = cv2.VideoCapture(s['value']) + frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) + video.release() + if frame_count < self.nframe: + new_frame_count = frame_count // self.FRAME_FACTOR * self.FRAME_FACTOR + print(f"use {new_frame_count} for {s['value']}") + item['nframes'] = new_frame_count + else: + item['nframes'] = self.nframe + elif s['type'] == 'text': + item = {'type': 'text', 'text': s['value']} + else: + raise ValueError(f"Invalid message type: {s['type']}, {s}") + content.append(item) + return content + + def generate_inner(self, message, dataset=None): + try: + from qwen_vl_utils import process_vision_info + except Exception as err: + logging.critical("qwen_vl_utils not found, please install it via 'pip install qwen-vl-utils'") + raise err + + messages = [] + if self.system_prompt is not None: + messages.append({'role': 'system', 'content': self.system_prompt}) + messages.append({'role': 'user', 'content': self._prepare_content(message, dataset=dataset)}) + if self.verbose: + print(f'\033[31m{messages}\033[0m') + + text = self.processor.apply_chat_template([messages], tokenize=False, add_generation_prompt=True) + images, videos = process_vision_info([messages]) + inputs = self.processor(text=text, images=images, videos=videos, padding=True, return_tensors='pt') + inputs = inputs.to('cuda') + + generated_ids = self.model.generate( + **inputs, + **self.generate_kwargs, + ) + generated_ids = [ + output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, generated_ids) + ] + out = self.processor.tokenizer.batch_decode( + generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + raw_response = out[0] + response = raw_response + if self.post_process: + response = extract_response_for_eval(raw_response, verbose=self.verbose) + if self.verbose: + print(f'\033[32m{response}\033[0m') + return response diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/wemm.py b/VLMEvalKit-sudoku/vlmeval/vlm/wemm.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea8d736d00059c7735388155e742014f2d898a6 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/wemm.py @@ -0,0 +1,71 @@ +import torch +from PIL import Image +import sys +from ..smp import * +from .base import BaseModel +from ..dataset import DATASET_TYPE +from transformers import AutoModel, GenerationConfig + + +class WeMM(BaseModel): + def __init__(self, model_path='feipengma/WeMM', **kwargs): + self.wemm = AutoModel.from_pretrained(model_path, torch_dtype=torch.bfloat16, trust_remote_code=True) + self.wemm.cuda() + self.wemm.eval() + torch.cuda.empty_cache() + + def use_custom_prompt(self, dataset): + assert dataset is not None + if DATASET_TYPE(dataset) == 'MCQ': + return True + return False + + def build_prompt(self, line, dataset=None): + assert self.use_custom_prompt(dataset) + assert dataset is None or isinstance(dataset, str) + tgt_path = self.dump_image(line, dataset) + question = line['question'] + hint = line['hint'] if ('hint' in line and not pd.isna(line['hint'])) else None + if hint is not None: + question = hint + '\n' + question + options = { + cand: line[cand] + for cand in string.ascii_uppercase + if cand in line and not pd.isna(line[cand]) + } + for key, item in options.items(): + question += f'\n{key}. {item}' + prompt = question + + if len(options): + prompt += ( + '\n请直接回答选项字母。' if cn_string(prompt) else + "\nAnswer with the option's letter from the given choices directly." + ) + else: + prompt += '\n请直接回答问题。' if cn_string(prompt) else '\nAnswer the question directly.' + + message = [dict(type='text', value=prompt)] + message.extend([dict(type='image', value=p) for p in tgt_path]) + return message + + def generate_inner(self, message, dataset=None): + prompt, image_path = self.message_to_promptimg(message, dataset=dataset) + + if dataset == 'HallusionBench': + prompt = prompt + ' Please answer yes or no. Answer the question using a single word or phrase.' + + gen_config = None + if dataset == 'MMVet': + gen_config = GenerationConfig( + max_new_tokens=512, + do_sample=True, + temperatures=0.7, + num_beams=3, + eos_token_id=self.wemm.tokenizer.eos_token_id, + pad_token_id=self.wemm.tokenizer.pad_token_id + if self.wemm.tokenizer.pad_token_id is not None else self.wemm.tokenizer.eos_token_id, + ) + pred = self.wemm.mm_generate(image_path, prompt, gen_config) + + return pred diff --git a/VLMEvalKit-sudoku/vlmeval/vlm/xgen_mm.py b/VLMEvalKit-sudoku/vlmeval/vlm/xgen_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..3d330b6dc48dcd60a85176fc99988972eddda119 --- /dev/null +++ b/VLMEvalKit-sudoku/vlmeval/vlm/xgen_mm.py @@ -0,0 +1,81 @@ +from PIL import Image +import torch + +from .base import BaseModel +from ..smp import * + + +class XGenMM(BaseModel): + + INSTALL_REQ = False + INTERLEAVE = True + + def __init__(self, model_path='Salesforce/xgen-mm-phi3-mini-instruct-interleave-r-v1.5', **kwargs): + try: + from transformers import AutoModelForVision2Seq, AutoTokenizer, AutoImageProcessor + except Exception as err: + logging.critical('Please install the latest version transformers.') + raise err + + model = AutoModelForVision2Seq.from_pretrained( + model_path, device_map='cuda', trust_remote_code=True, torch_dtype='auto' + ).eval() + + tokenizer = AutoTokenizer.from_pretrained( + model_path, trust_remote_code=True, use_fast=False, legacy=False + ) + tokenizer = model.update_special_tokens(tokenizer) + tokenizer.eos_token = '<|end|>' + tokenizer.padding_side = 'left' + image_processor = AutoImageProcessor.from_pretrained(model_path, trust_remote_code=True) + self.model = model + self.image_processor = image_processor + self.tokenizer = tokenizer + self.kwargs = kwargs + + def apply_prompt_template(self, query): + s = ( + '<|system|>\nA chat between a curious user and an artificial intelligence assistant. ' + "The assistant gives helpful, detailed, and polite answers to the user's questions.<|end|>\n" + f'<|user|>\n{query}<|end|>\n<|assistant|>\n' + ) + return s + + def generate_inner(self, message, dataset=None): + + content, images, image_sizes = '', [], [] + + for msg in message: + if msg['type'] == 'text': + content += msg['value'] + elif msg['type'] == 'image': + image = Image.open(msg['value']).convert('RGB') + images.append(self.image_processor([image], image_aspect_ratio='anyres')['pixel_values'].to('cuda')) + image_sizes.append(image.size) + content += ' ' + + inputs = {'pixel_values': [images]} + prompt = self.apply_prompt_template(content) + language_inputs = self.tokenizer([prompt], return_tensors='pt').to('cuda') + inputs.update(language_inputs) + + generation_args = { + 'max_new_tokens': 1024, + 'temperature': 0.0, + 'do_sample': False, + 'top_p': None, + 'num_beams': 1 + } + generation_args.update(self.kwargs) + + generate_ids = self.model.generate( + **inputs, image_size=[image_sizes], + pad_token_id=self.tokenizer.pad_token_id, + eos_token_id=self.tokenizer.eos_token_id, + **generation_args + ) + + # remove input tokens + response = self.tokenizer.decode(generate_ids[0], skip_special_tokens=True).split('<|end|>')[0] + + return response