Add evaluation files

This commit is contained in:
Catpp01 committed 2025-07-08 17:49:43 +08:00
1 parent 6708d677dc
commit 4ee7f3f43e
510 files changed
+94282

No files matched your search

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 KiB

+19
View File
@@ -0,0 +1,19 @@
Strategy_Instruction:
CoT: "Please solve the problem step by step."
Directly: "Please ensure that your output only contains the final answer without any additional content (such as intermediate reasoning steps)."
multi_choice_format:
"{context}
{question}
{options}
Answer with the option's letter from the given choices and put the letter in one \"\\boxed{{}}\". "
open_ended_format:
"{context}
{question}
Answer the question using a single word or phrase and put the answer in one \"\\boxed{{}}\". "
+56
View File
@@ -0,0 +1,56 @@
import yaml
import json
def load_yaml(file_path):
with open(file_path, 'r') as stream:
try:
yaml_dict = yaml.safe_load(stream)
return yaml_dict
except yaml.YAMLError as exc:
print(exc)
return None
def verify_response(response):
if isinstance(response, str):
response = response.strip()
if response == "" or response is None:
return False
if "Response Error" in response:
return False
return True
def build_query(sample, config, strategy):
"""Build the text query by combining the context, question and options. The <image_n> token is still there"""
context = sample['context']
question = sample['question']
example = ""
res_dict = {}
if sample['type'].lower() == 'multiple choice':
options = sample['options']
start_chr = 'A'
for option in options:
example += f"{start_chr}: {option}\n"
start_chr = chr(ord(start_chr) + 1)
empty_prompt_sample_structure = config['multi_choice_format']
empty_prompt = empty_prompt_sample_structure.format(context=context, question=question, options=example)
if strategy == 'CoT':
res_dict['query'] = empty_prompt + config['Strategy_Instruction']['CoT']
else:
res_dict['query'] = empty_prompt + config['Strategy_Instruction']['Directly']
res_dict['gt_content'] = options[ord(sample['answer'].upper()) - ord('A')]
else:
empty_prompt_sample_structure = config['open_ended_format']
empty_prompt = empty_prompt_sample_structure.format(context=context, question=question)
if strategy == 'CoT':
res_dict['query'] = empty_prompt + config['Strategy_Instruction']['CoT']
else:
res_dict['query'] = empty_prompt + config['Strategy_Instruction']['Directly']
res_dict['gt_content'] = sample['answer']
# append existing key and value in data
res_dict.update(sample)
return res_dict
+130
View File
@@ -0,0 +1,130 @@
import argparse
import logging
import os
import json
from collections import defaultdict
def gen_score(input_file, output_file):
with open(input_file, "r") as f:
data = json.load(f)
total_correct = 0
total_count = 0
subject_stats = defaultdict(lambda: {"correct": 0, "total": 0})
type_stats = defaultdict(lambda: {"correct": 0, "total": 0})
category_stats = defaultdict(lambda: defaultdict(lambda: {"correct": 0, "total": 0}))
task_stats = defaultdict(lambda: {"correct": 0, "total": 0})
for key, entry in data.items():
total_count += 1
is_correct = 1 if entry["true_false"] else 0
total_correct += is_correct
subject = entry["subject"]
question_type = entry["type"].lower()
if entry["category"]:
if subject == "Coding":
category_list = entry["category"].split(';')
for category in category_list:
category = category.strip()
category_stats[subject][category]["total"] += 1
category_stats[subject][category]["correct"] += is_correct
else:
category = entry["category"]
category_stats[subject][category]["total"] += 1
category_stats[subject][category]["correct"] += is_correct
if entry["task"]:
task = subject + '_' + entry["task"]
task_stats[task]["total"] += 1
task_stats[task]["correct"] += is_correct
subject_stats[subject]["total"] += 1
subject_stats[subject]["correct"] += is_correct
type_stats[question_type]["total"] += 1
type_stats[question_type]["correct"] += is_correct
average_accuracy = total_correct / total_count if total_count > 0 else 0
logging.info(f"Average accuracy: {average_accuracy}")
score = {
"average": {
"accuracy": average_accuracy,
"correct": total_correct,
"total": total_count
},
"subject": {
subject: {
"accuracy": stats["correct"] / stats["total"] if stats["total"] > 0 else 0,
"correct": stats["correct"],
"total": stats["total"]
} for subject, stats in subject_stats.items()
},
"question_type": {
question_type: {
"accuracy": stats["correct"] / stats["total"] if stats["total"] > 0 else 0,
"correct": stats["correct"],
"total": stats["total"]
} for question_type, stats in type_stats.items()
},
"category": {
subject:{
category: {
"accuracy": stats["correct"] / stats["total"] if stats["total"] > 0 else 0,
"correct": stats["correct"],
"total": stats["total"]
} for category, stats in categories.items()
}for subject, categories in category_stats.items()
},
"task": {
task: {
"accuracy": stats["correct"] / stats["total"] if stats["total"] > 0 else 0,
"correct": stats["correct"],
"total": stats["total"]
} for task, stats in task_stats.items()
}
}
with open(output_file, "w") as f:
f.write(json.dumps(score, indent=2))
def main():
parser = argparse.ArgumentParser()
# output
parser.add_argument('--results_dir', type=str, default='/mnt/datasets_vlm/yunzhuo.hao/benchmarks/EMMA/results/EMMA-mini/open-source')
args = parser.parse_args()
for root, dirs, files in os.walk(args.results_dir):
for file in files:
if file.endswith(".json") and not file.endswith("_result.json"):
gen_score(os.path.join(root, file), os.path.join(root, file).replace('.json', '_result.json'))
if __name__ == "__main__":
logging.basicConfig(
level=os.environ.get("LOGLEVEL", "INFO").upper(),
format="[%(name)s] %(message)s",
datefmt="[%X]"
)
logger_blocklist = [
"asyncio",
"azure",
"azureml",
"datasets",
"httpx",
"httpcore",
"filelock",
"fsspec",
"msal",
"msrest",
"openai",
"PIL",
"urllib3",
]
for module in logger_blocklist:
logging.getLogger(module).setLevel(logging.WARNING)
main()
+199
View File
@@ -0,0 +1,199 @@
import argparse
import json
import logging
import os
from tqdm import tqdm
from utils import *
import re
import time
def fast_extract_answer(response) :
response = response.strip()
# Direct Strategy Multi-Choice
# A / A: / A.
for ch in 'ABCDEFGH':
if response.upper() == ch or response.startswith(f'{ch}:') or response.startswith(f'{ch}.'):
return ch
# Direct Strategy Open-ended
# 1
if is_number(response):
return response
# CoT strategy
if 'boxed{' in response:
try:
model_answers = extract_full_boxed_content(response)
if model_answers:
# for coding
# \\boxed{\\text{}}
try:
text_content = re.findall(r'\\text{(.*?)}', model_answers[-1])
if text_content:
return text_content[-1].strip()
except Exception:
pass
return model_answers[-1].strip()
except Exception:
pass
# for Coding
# the correct answer is\n D.
for flag in ['final answer is', 'correct answer is', 'answer should be', 'answer is', 'answer:']:
if flag in response.lower():
try:
model_answer = response.lower().split(flag)[-1].strip()
return model_answer.split('\n')[0].split('.')[0]
except Exception:
pass
return ""
def create_test_prompt(score_prompt, problem, label):
score_prompt = score_prompt.strip()
response = problem[label]
answer = problem['answer']
full_prompt = f'{score_prompt}\n' + f'Response: {response}\n' + f'Answer: {answer}\n' + 'Correct_or_not:'
return full_prompt
def call_gpt(client, model, user_prompt):
attempt = 0
while attempt < 5:
try:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "user", "content": user_prompt}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Attempt {attempt + 1} failed: {e}")
if 'error' in str(e) and 'message' in str(e):
error_message = str(e)
if 'The server had an error processing your request.' in error_message:
sleep_time = 30
logging.error(f"Server error, retrying in {sleep_time}s...")
time.sleep(sleep_time)
elif 'Please try again in ' in error_message:
sleep_time = float(error_message.split('Please try again in ')[1].split('s.')[0])
logging.error(f"Rate limit exceeded, retrying in {sleep_time * 2}s...")
time.sleep(sleep_time * 2)
else:
print("Unknown error, skipping this request.")
break
attempt += 1
def gen_true_false(answer_file, args):
logging.info(f"Reading {answer_file}.....")
label = args.response_label
if args.gpt_eval:
from openai import OpenAI
client = OpenAI(api_key=args.api_key)
with open(answer_file, "r") as f:
results = json.load(f)
full_pids = list(results.keys())
skip_pids = []
for pid, problem in results.items():
flag = problem.get('true_false')
if flag is not None:
skip_pids.append(problem['pid'])
if args.rerun:
test_pids = full_pids
else:
if len(skip_pids) > 0:
logging.info(
f"Found existing results file with {len(skip_pids)} problems with valid responses. Skipping these problems..."
)
test_pids = [pid for pid in full_pids if pid not in skip_pids]
logging.info(f"Number of test problems to run: {len(test_pids)}")
for i, pid in enumerate(tqdm(test_pids)):
problem = results[pid]
flag = False
if label not in problem or not problem[label]:
results[pid]['extraction'] = None
results[pid]['true_false'] = False
continue
if args.gpt_eval:
user_prompt = create_test_prompt(score_demo_prompt, problem, label)
flag_cache = call_gpt(client, args.model, user_prompt)
results[pid]['gpt_eval'] = flag_cache
if flag_cache.lower() == 'correct':
flag = True
else:
flag = False
else:
model_answer = fast_extract_answer(problem[label])
results[pid]['extraction'] = model_answer
if is_equal(model_answer, results[pid]['answer']) or is_equal(model_answer, results[pid]['gt_content']):
flag = True
results[pid]['true_false'] = flag
if (i % args.save_every == 0 and i > 0) or i == len(test_pids) - 1:
with open(answer_file, "w") as f:
f.write(json.dumps(results, indent=2))
logging.info(f"Saved results to {answer_file}")
with open(answer_file, "w") as f:
f.write(json.dumps(results, indent=2))
logging.info(f"Saved results to {answer_file}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--results_dir', type=str, default='/mnt/datasets_vlm/yunzhuo.hao/benchmarks/EMMA/results/EMMA-mini/open-source')
parser.add_argument('--response_label', type=str, default='response', help='response label for the input file')
parser.add_argument('--rerun', action='store_true', help='rerun the answer extraction')
parser.add_argument('--save_every', type=int, default=10, help='save every n problems')
parser.add_argument('--gpt_eval', action='store_true', help='use gpt to evaluate')
parser.add_argument('--api_key', type=str, default="")
parser.add_argument('--model', type=str, default="chatgpt-4o-latest")
args = parser.parse_args()
logging.info("Starting to extract answers.......")
for root, dirs, files in os.walk(args.results_dir):
for file in files:
if file.endswith(".json") and not file.endswith("_result.json"):
gen_true_false(os.path.join(root, file), args)
if __name__ == "__main__":
logging.basicConfig(
level=os.environ.get("LOGLEVEL", "INFO").upper(),
format="[%(name)s] %(message)s",
datefmt="[%X]"
)
logger_blocklist = [
"asyncio",
"azure",
"azureml",
"datasets",
"httpx",
"httpcore",
"filelock",
"fsspec",
"msal",
"msrest",
"openai",
"PIL",
"urllib3",
]
for module in logger_blocklist:
logging.getLogger(module).setLevel(logging.WARNING)
main()
+100
View File
@@ -0,0 +1,100 @@
from latex2sympy2 import latex2sympy
import re
from sympy import simplify
from word2number import w2n
def verify_extraction(extraction):
extraction = extraction.strip()
if extraction == "" or extraction == None:
return False
return True
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def extract_full_boxed_content(s):
"""
Extract the full content inside \boxed{}, handling nested braces {{}} properly.
"""
results = []
i = 0
while i < len(s):
if s[i:i + 7] == r'\boxed{':
brace_stack = []
start = i + 7
i = start
while i < len(s):
if s[i] == '{':
brace_stack.append(i)
elif s[i] == '}':
if brace_stack:
brace_stack.pop()
else:
results.append(s[start:i])
break
i += 1
i += 1
return results
def is_equal(md_ans, gt_ans):
md_ans = md_ans.lower()
gt_ans = gt_ans.lower()
if md_ans.strip() == gt_ans.strip():
return True
try:
md_ans_cache = str(w2n.word_to_num(md_ans))
if md_ans_cache.strip() == gt_ans.strip():
return True
except ValueError:
pass
# For Math
try:
# Parse LaTeX expressions into sympy and compare numerical values
md_sympy = latex2sympy(md_ans)
gt_sympy = latex2sympy(gt_ans)
# Compare evaluated results, rounded to 2 decimal places
if round(float(md_sympy.evalf()), 2) == round(float(gt_sympy.evalf()), 2):
return True
# Additionally, compare simplified symbolic expressions
if simplify(md_sympy - gt_sympy) == 0:
return True
except Exception:
pass # Ignore parsing errors or evaluation failures
return False
score_demo_prompt = """Please read the following example. Then determine whether the response is correct and type it
at the end of the prompt. It is worth noting that the final answer in the response is usually in \\boxed{},
You only need to compare the final answer in the response with the answer, without considering the logical
correctness of the response itself.
Response: The correct answer is:\n\nA
Answer: A
Correct_or_not: Correct
Response: The correct option is:\n\n\\[\n\\boxed{E}\n\\]
Answer: C
Correct_or_not: Incorrect
"""
+185
View File
@@ -0,0 +1,185 @@
import argparse
import json
import os
import logging
from tqdm import tqdm
from datasets import load_dataset, concatenate_datasets
from data_utils import load_yaml, verify_response, build_query
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_name', type=str, default='luckychao/EMMA')
parser.add_argument('--subject', nargs='+', type=str, required=True)
parser.add_argument('--split', type=str, default='test')
parser.add_argument('--strategy', type=str, default='CoT', choices=['CoT', 'Direct'])
parser.add_argument('--config_path', type=str, default="configs/gpt.yaml")
parser.add_argument('--output_path', type=str, default='results/test-gemini.json')
parser.add_argument('--save_every', type=int, default=20, help='save every n problems')
parser.add_argument('--rerun', action='store_true', help='rerun the answer generation')
# Remote model
parser.add_argument('--model', type=str, default="chatgpt-4o-latest", help='remote llm engine',
choices=['chatgpt-4o-latest', 'claude-3-5-sonnet-latest', 'gemini-2.0-flash-exp','gemini-2.0-flash-thinking-exp-1219'])
parser.add_argument('--api_key', type=str, default='')
# Local model
parser.add_argument('--model_path', type=str, default='', help="local model path or huggingface model name")
parser.add_argument('--max_tokens', type=int, default=4096)
parser.add_argument('--temperature', type=float, default=0.7)
args = parser.parse_args()
# Load Dataset
logging.info(f"Loading dataset {args.dataset_name}, subject: {args.subject}")
sub_dataset_list = []
for subj in args.subject:
sub_dataset = load_dataset(args.dataset_name, subj, split=args.split)
sub_dataset_list.append(sub_dataset)
dataset = concatenate_datasets(sub_dataset_list)
# Load Config
logging.info(f"Loading config")
config = load_yaml(args.config_path)
# Load Model
# If we were given a custom path, load that model, otherwise use a remote service model
if args.model_path:
logging.info(f"Loading local model {args.model_path}")
if 'llava' in args.model_path.lower():
from models import llava
model = llava.Llava_Model(args.model_path, temperature=args.temperature, max_tokens=args.max_tokens)
if 'qwen2.5-vl' in args.model_path.lower():
from models import qwen
model = qwen.Qwen2_5_Model(args.model_path, temperature=args.temperature, max_tokens=args.max_tokens)
# if 'qwen2-vl' or 'qvq' in args.model_path.lower():
# from models import qwen
# model = qwen.Qwen_Model(args.model_path, temperature=args.temperature, max_tokens=args.max_tokens)
if 'internvl' in args.model_path.lower():
from models import internvl
model = internvl.Internvl_Model(args.model_path, temperature=args.temperature, max_tokens=args.max_tokens)
if 'skywork' in args.model_path.lower() or "r1v3" in args.model_path.lower():
from models import skywork
model = skywork.Skywork_Model(args.model_path, temperature=args.temperature, max_tokens=args.max_tokens)
else:
logging.info(f"Loading {args.model}")
if 'gpt' in args.model.lower():
from openai import OpenAI
from models import gpt
client = OpenAI(api_key=args.api_key)
model = gpt.GPT_Model(client, args.model, temperature=args.temperature, max_tokens=args.max_tokens)
elif 'claude' in args.model.lower():
from anthropic import Anthropic
from models import claude
client = Anthropic(api_key=args.api_key)
model = claude.Claude_Model(client, args.model, temperature=args.temperature, max_tokens=args.max_tokens)
elif 'gemini' in args.model.lower():
from openai import OpenAI
from models import gpt
client = OpenAI(
api_key=args.api_key,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
model = gpt.GPT_Model(client, args.model, temperature=args.temperature, max_tokens=args.max_tokens)
logging.info(f"Model loaded!")
if os.path.exists(args.output_path):
logging.info("Results already exists.")
logging.info(f"Reading {args.output_path}")
with open(args.output_path, 'r') as f:
results = json.load(f)
else:
results = {}
skip_pids = []
if not args.rerun and results:
for pid, data in results.items():
if 'response' in data and verify_response(data['response']):
skip_pids.append(pid)
if len(skip_pids) > 0:
logging.info(
f"Found existing results file with {len(skip_pids)} problems with valid responses. Skipping these problems...")
logging.info(f"Starting to generate.....")
for idx, sample in enumerate(tqdm(dataset)):
pid = sample['pid']
if skip_pids and pid in skip_pids:
continue
sample = build_query(sample, config, args.strategy)
problem: dict = sample.copy()
for i in range(1, 6):
problem.pop('image_' + str(i))
try:
response = model.get_response(sample)
results[pid] = problem
results[pid]['response'] = response
except Exception as e:
logging.error(f"Error in generating answer for {pid}")
logging.error(e)
results[pid] = problem
results[pid]['error'] = str(e)
if idx == 2 or (idx % args.save_every == 0 and idx > 0) or idx == len(dataset) - 1:
try:
with open(args.output_path, 'w') as f:
f.write(json.dumps(results, indent=2))
logging.info(f"Save results to {args.output_path}")
except Exception as e:
logging.info(f"Error in saving {args.output_path}")
logging.info(e)
with open(args.output_path, 'w') as f:
f.write(json.dumps(results, indent=2))
logging.info(f"Save results to {args.output_path}")
logging.info("End Generation......")
if __name__ == "__main__":
logging.basicConfig(
level=os.environ.get("LOGLEVEL", "INFO").upper(),
format="[%(name)s] %(message)s",
datefmt="[%X]"
)
logger_blocklist = [
"asyncio",
"azure",
"azureml",
"datasets",
"httpx",
"httpcore",
"filelock",
"fsspec",
"msal",
"msrest",
"openai",
"PIL",
"urllib3",
]
for module in logger_blocklist:
logging.getLogger(module).setLevel(logging.WARNING)
main()
View File
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+81
View File
@@ -0,0 +1,81 @@
import logging
import re
import base64
from io import BytesIO
from anthropic import Anthropic
def encode_image_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
def create_message(sample):
query = sample['query']
all_contents = []
matches = re.findall(r"<(image_\d+)>", query)
split_text = re.split(r"<image_\d+>", query)
for i, fragment in enumerate(split_text):
if fragment.strip():
all_contents.extend([
{"type": "text", "text": fragment}
])
if i < len(matches):
if sample[matches[i]]:
img_base64 = encode_image_to_base64(sample[matches[i]])
all_contents.extend([
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": img_base64
}
}
])
else:
logging.error(
f"The image token {matches[i]} is in the query, but there is no corresponding image provided by the data")
messages = [
{
"role": "user",
"content": all_contents
}
]
return messages
# build claude class
class Claude_Model():
def __init__(
self,
client: Anthropic,
model="claude-3-5-sonnet-latest",
temperature=0,
max_tokens=1024
):
self.client = client
self.model = model
self.temperature = temperature
self.max_tokens = max_tokens
def get_response(self, sample):
messages = create_message(sample)
try:
v_response = self.client.messages.create(
model=self.model,
max_tokens=self.max_tokens,
temperature=self.temperature,
messages=messages
)
response = v_response.content[0].text
return response
except Exception as e:
print(e)
return None
+103
View File
@@ -0,0 +1,103 @@
import logging
import re
import base64
from io import BytesIO
import time
from openai import OpenAI
def encode_image_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
def create_message(sample):
query = sample['query']
all_contents = []
matches = re.findall(r"<(image_\d+)>", query)
split_text = re.split(r"<image_\d+>", query)
for i, fragment in enumerate(split_text):
if fragment.strip():
all_contents.extend([
{"type": "text", "text": fragment}
])
if i < len(matches):
if sample[matches[i]]:
img_base64 = encode_image_to_base64(sample[matches[i]])
all_contents.extend([
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{img_base64}"
}
}
])
else:
logging.error(
f"The image token {matches[i]} is in the query, but there is no corresponding image provided by the data")
messages = [
{
"role": "user",
"content": all_contents
}
]
return messages
# build gpt class
class GPT_Model:
def __init__(
self,
client: OpenAI,
model="chatgpt-4o-latest",
temperature=0,
max_tokens=1024,
retry_attempts = 5
):
self.client = client
self.model = model
self.temperature = temperature
self.max_tokens = max_tokens
self.retry_attempts = retry_attempts
def get_response(self, sample):
attempt = 0
messages = create_message(sample)
while attempt < self.retry_attempts:
try:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Attempt {attempt + 1} failed: {e}")
if 'error' in str(e) and 'message' in str(e):
error_message = str(e)
if 'The server had an error processing your request.' in error_message:
sleep_time = 30
logging.error(f"Server error, retrying in {sleep_time}s...")
time.sleep(sleep_time)
elif 'Please try again in ' in error_message:
sleep_time = float(error_message.split('Please try again in ')[1].split('s.')[0])
logging.error(f"Rate limit exceeded, retrying in {sleep_time * 2}s...")
time.sleep(sleep_time * 2)
elif 'RESOURCE_EXHAUSTED' in error_message:
sleep_time = 30
logging.error(f"Gemini rate limit, retrying in {sleep_time}s...")
time.sleep(sleep_time)
else:
print("Unknown error, skipping this request.")
break
attempt += 1
return None
+172
View File
@@ -0,0 +1,172 @@
import re
import logging
import torch
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
from transformers import AutoModel, AutoTokenizer
import math
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
def split_model(model_name):
device_map = {}
world_size = torch.cuda.device_count()
num_layers = {
'InternVL2-1B': 24, 'InternVL2-2B': 24, 'InternVL2-4B': 32, 'InternVL2-8B': 32,
'InternVL2-26B': 48, 'InternVL2-40B': 60, 'InternVL2-Llama3-76B': 80}[model_name]
# Since the first GPU will be used for ViT, treat it as half a GPU.
num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
num_layers_per_gpu = [num_layers_per_gpu] * world_size
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
layer_cnt = 0
for i, num_layer in enumerate(num_layers_per_gpu):
for j in range(num_layer):
device_map[f'language_model.model.layers.{layer_cnt}'] = i
layer_cnt += 1
device_map['vision_model'] = 0
device_map['mlp1'] = 0
device_map['language_model.model.tok_embeddings'] = 0
device_map['language_model.model.embed_tokens'] = 0
device_map['language_model.output'] = 0
device_map['language_model.model.norm'] = 0
device_map['language_model.lm_head'] = 0
device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
return device_map
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=12, 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, input_size=448, max_num=12):
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 process_query(sample):
query = sample['query']
matches = re.findall(r"<(image_\d+)>", query)
modified_query = re.sub(r"<image_\d+>", "<image>", query)
images = []
for match in matches:
if sample[match]:
images.append(sample[match])
else:
logging.error(f"The image token <{match}> is in the query, but there is no corresponding image provided by the data")
return modified_query, images
class Internvl_Model:
def __init__(
self,
model_path,
temperature=0,
max_tokens=1024
):
self.temperature = temperature
self.max_tokens = max_tokens
self.device_map = split_model('InternVL2-Llama3-76B')
self.model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True,
device_map=self.device_map).eval()
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False)
def get_response(self, sample):
model = self.model
tokenizer = self.tokenizer
try:
query, images = process_query(sample)
pixel_values_list = []
num_patches_list = []
for image in images:
pixel_value = load_image(image, max_num=12).to(torch.bfloat16).cuda()
pixel_values_list.append(pixel_value)
num_patches_list.append(pixel_value.size(0))
pixel_values = torch.cat(pixel_values_list, dim=0)
generation_config = dict(max_new_tokens=self.max_tokens, do_sample=True, temperature=self.temperature)
# single-image single-round conversation
response = model.chat(tokenizer, pixel_values, query, generation_config,
num_patches_list=num_patches_list)
return response
except Exception as e:
print(e)
return None
+82
View File
@@ -0,0 +1,82 @@
import re
import logging
import torch
from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
def create_message(sample):
query = sample['query']
all_contents = []
matches = re.findall(r"<(image_\d+)>", query)
split_text = re.split(r"<image_\d+>", query)
images = []
for i, fragment in enumerate(split_text):
if fragment.strip():
all_contents.extend([
{"type": "text", "text": fragment}
])
if i < len(matches):
if sample[matches[i]]:
all_contents.extend([
{"type": "image"}
])
images.append(sample[matches[i]])
else:
logging.error(
f"The image token {matches[i]} is in the query, but there is no corresponding image provided by the data")
messages = [
{
"role": "user",
"content": all_contents
}
]
return messages, images
class Llava_Model:
def __init__(
self,
model_path,
temperature=0,
max_tokens=1024
):
self.temperature = temperature
self.max_tokens = max_tokens
self.model = LlavaOnevisionForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.float16,
device_map="auto",
use_flash_attention_2=True
)
self.processor = AutoProcessor.from_pretrained(model_path)
def get_response(self, sample):
model = self.model
processor = self.processor
try:
messages, images = create_message(sample)
input_text = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(
images=images,
text=input_text,
add_special_tokens=False,
return_tensors="pt"
).to(model.device, torch.float16)
output = model.generate(**inputs, do_sample=True, temperature=self.temperature, max_new_tokens=self.max_tokens)
response = processor.decode(output[0], skip_special_tokens=True)
assistant_index = response.find("assistant")
if assistant_index != -1:
final_answer = response[assistant_index + len("assistant"):].strip()
else:
final_answer = response.strip()
return final_answer
except Exception as e:
print(e)
return None
+156
View File
@@ -0,0 +1,156 @@
import re
import logging
import base64
from io import BytesIO
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
def encode_image_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return img_str
def create_message(sample):
query = sample['query']
all_contents = []
matches = re.findall(r"<(image_\d+)>", query)
split_text = re.split(r"<image_\d+>", query)
for i, fragment in enumerate(split_text):
if fragment.strip():
all_contents.extend([
{"type": "text", "text": fragment}
])
if i < len(matches):
if sample[matches[i]]:
img_base64 = encode_image_to_base64(sample[matches[i]])
all_contents.extend([
{
"type": "image",
"image": f"data:image/png;base64,{img_base64}"
}
])
else:
logging.error(
f"The image token {matches[i]} is in the query, but there is no corresponding image provided by the data")
messages = [
{
"role": "user",
"content": all_contents
}
]
return messages
class Qwen_Model:
def __init__(
self,
model_path,
temperature=0,
max_tokens=1024
):
self.model_path = model_path
self.temperature = temperature
self.max_tokens = max_tokens
self.model = Qwen2VLForConditionalGeneration.from_pretrained(self.model_path, torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="auto", )
self.processor = AutoProcessor.from_pretrained(self.model_path)
def get_response(self, sample):
model = self.model
processor = self.processor
try:
messages = create_message(sample)
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True, add_vision_id=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
inputs = inputs.to("cuda")
# Inference: Generation of the output
generated_ids = 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 = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
return response[0]
except Exception as e:
print(e)
return None
class Qwen2_5_Model:
def __init__(
self,
model_path="Qwen/Qwen2.5-VL-72B-Instruct",
temperature=0,
max_tokens=1024
):
self.model_path = model_path
self.temperature = temperature
self.max_tokens = max_tokens
self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
self.model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="auto"
)
self.processor = AutoProcessor.from_pretrained(self.model_path)
def get_response(self, sample):
model = self.model
processor = self.processor
try:
messages = create_message(sample)
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True, add_vision_id=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
inputs = inputs.to("cuda")
# Inference: Generation of the output
generated_ids = 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 = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
return response[0]
except Exception as e:
print(e)
return None
+165
View File
@@ -0,0 +1,165 @@
import torch
from transformers import AutoModel, AutoTokenizer
import argparse
import math
import torch
import torchvision.transforms as T
from PIL import Image
from torchvision.transforms.functional import InterpolationMode
from transformers import AutoConfig
import re
import logging
import traceback
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=12, image_size=448, use_thumbnail=False):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
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])
target_aspect_ratio = find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
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]
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_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, input_size=448, max_num=12):
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 split_model(model_path):
device_map = {}
world_size = torch.cuda.device_count()
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
num_layers = config.llm_config.num_hidden_layers
num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
num_layers_per_gpu = [num_layers_per_gpu] * world_size
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
layer_cnt = 0
for i, num_layer in enumerate(num_layers_per_gpu):
for j in range(num_layer):
device_map[f'language_model.model.layers.{layer_cnt}'] = i
layer_cnt += 1
device_map['vision_model'] = 0
device_map['mlp1'] = 0
device_map['language_model.model.tok_embeddings'] = 0
device_map['language_model.model.embed_tokens'] = 0
device_map['language_model.output'] = 0
device_map['language_model.model.norm'] = 0
device_map['language_model.model.rotary_emb'] = 0
device_map['language_model.lm_head'] = 0
device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
return device_map
def process_query(sample):
query = sample['query']
matches = re.findall(r"<(image_\d+)>", query)
modified_query = re.sub(r"<image_\d+>", "<image>", query)
images = []
for match in matches:
if sample[match]:
images.append(sample[match])
else:
logging.error(f"The image token <{match}> is in the query, but there is no corresponding image provided by the data")
return modified_query, images
class Skywork_Model:
def __init__(
self,
model_path,
temperature=0,
max_tokens=1024
):
self.temperature = temperature
self.max_tokens = max_tokens
self.device_map = split_model(model_path)
self.model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
load_in_8bit=False,
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True,
device_map=self.device_map
).eval()
self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False)
def get_response(self, sample):
model = self.model
tokenizer = self.tokenizer
try:
query, images = process_query(sample)
pixel_values_list = []
num_patches_list = []
for image in images:
pixel_value = load_image(image, max_num=12).to(torch.bfloat16).cuda()
pixel_values_list.append(pixel_value)
num_patches_list.append(pixel_value.size(0))
pixel_values = torch.cat(pixel_values_list, dim=0)
generation_config = dict(max_new_tokens=self.max_tokens, do_sample=True, temperature=self.temperature)
# single-image single-round conversation
response = model.chat(tokenizer, pixel_values, query, generation_config,
num_patches_list=num_patches_list)
return response
except Exception as e:
error_message = traceback.format_exc()
print(error_message)
return None
+57
View File
@@ -0,0 +1,57 @@
#!/bin/bash
cd ./eval/EMMA
SUBJECT="Math Coding Physics Chemistry" # You can use multiple subjects separated by spaces
STRATEGY="CoT" # CoT or Direct
SUBJECT_FORMATTED=$(echo $SUBJECT | tr ' ' '_')
MODEL_PATH="/path/to/your/model/path"
MODEL=$(basename "$MODEL_PATH")
DATASET_NAME="/path/to/your/dataset/path"
MAX_TOKENS=64000
TEMPERATURE=0.7
SAVE_EVERY=3
SPLIT="test"
CONFIG_PATH="configs/gpt.yaml"
# Construct output and log file paths
OUTPUT_FILE="results/EMMA-mini/open-source/${MODEL}_${SUBJECT_FORMATTED}_${STRATEGY}.json"
# LOG_FILE="logs/${MODEL}_${SUBJECT_FORMATTED}_${STRATEGY}.log"
mkdir -p "$(dirname "$OUTPUT_FILE")"
# mkdir -p "$(dirname "$LOG_FILE")"
# Print constructed file paths for debugging
echo "==============================================="
echo "🚀 Starting Script Execution"
echo "-----------------------------------------------"
echo "---- Model: ${MODEL}"
echo "📁 Output File Path: ${OUTPUT_FILE}"
echo "📝 Log File Path: ${LOG_FILE}"
echo "==============================================="
# source ~/miniconda3/etc/profile.d/conda.sh
# conda activate internvl
# pip uninstall -y apex
# pip install timm
# pip install qwen_vl_utils
export CUDA_VISIBLE_DEVICES="0,1,2,3"
python generate_response.py \
--dataset_name $DATASET_NAME \
--subject $SUBJECT \
--split $SPLIT \
--strategy $STRATEGY \
--output_path $OUTPUT_FILE \
--model_path $MODEL_PATH \
--config_path $CONFIG_PATH \
--max_tokens $MAX_TOKENS \
--temperature $TEMPERATURE \
--save_every $SAVE_EVERY
# Completion message
echo "✅ Script launched successfully!"
echo "==============================================="
+4
View File
@@ -0,0 +1,4 @@
python evaluate.py \
--results_dir 'path_to_your_results_dir' \
--response_label 'response' \
--save_every 20
+7
View File
@@ -0,0 +1,7 @@
python evaluate.py \
--results_dir 'path_to_your_results_dir' \
--response_label 'response' \
--save_every 20 \
--gpt_eval \
--api_key '' \
--model 'chatgpt-4o-latest'
+47
View File
@@ -0,0 +1,47 @@
#!/bin/bash
python generate_response.py \
--dataset_name 'luckychao/EMMA' \
--split 'test' \
--subject 'Math' 'Physics' 'Chemistry' 'Coding' \
--strategy 'CoT' \
--config_path 'configs/gpt.yaml' \
--model 'remote-model-name' \
--api_key '' \
--output_path 'path_to_output_file' \
--max_tokens 4096 \
--temperature 0 \
--save_every 20
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
python generate_response.py \
--dataset_name 'luckychao/EMMA' \
--split 'test' \
--subject 'Math' 'Physics' 'Chemistry' 'Coding' \
--strategy 'CoT' \
--config_path 'configs/gpt.yaml' \
--model_path 'path_to_your_local_model' \
--output_path 'path_to_output_file' \
--max_tokens 4096 \
--temperature 0.7 \
--save_every 20
+128
View File
@@ -0,0 +1,128 @@
import argparse
import json
import logging
import os
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
import openai
import regex
from openai import OpenAI
# Initialize client
client = OpenAI(
api_key="xxx",
base_url="xxx"
)
# Setup logging format
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
def query_gpt_judge(prompt, model="gpt-4o", max_tokens=256, retries=5):
"""Query the OpenAI model with prompt and return Yes/No."""
messages = [{"role": "user", "content": prompt}]
for attempt in range(retries):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.5 * attempt,
max_tokens=max_tokens
)
result = response.choices[0].message.content.strip()
if result.lower() in {"yes", "no"}:
return result
except Exception as e:
logging.warning(f"Request failed (attempt {attempt + 1}): {e}")
return "no"
def create_comparison_prompt(data):
"""Build a prompt to compare model output and ground truth answer."""
template = """
You are given a question, the correct answer, and a model's answer. Decide whether the model's answer matches the correct answer.
Ignore formatting differences such as LaTeX syntax, symbols, or wrappers (e.g., \boxed, $...$). Focus only on semantic or mathematical correctness.
If the model's answer is correct, respond with "Yes". Otherwise, respond with "No". Only output "Yes" or "No".
Question:
{question}
---
Correct Answer:
{answer}
---
Model Answer:
{model_response}
---
"""
response = str(data["response"])
# Try to extract answer from XML or boxed format
match = re.search(r"<answer>(.*?)</answer>", response, re.DOTALL)
if match:
response = match.group(1).strip()
else:
boxed = regex.findall(r"\\boxed\{((?:[^{}]+|(?P<BRACES>\{(?:[^{}]+|(?P>BRACES))*\}))*?)\}", response, re.DOTALL)
response = boxed[-1][0].strip() if boxed else response
return template.format(
question=data["question"],
answer=data["answer"],
model_response=response
)
def evaluate_sample(problem):
"""Evaluate a single problem instance."""
prompt = create_comparison_prompt(problem)
logging.info(f"Evaluating ID: {problem['id']}")
verdict = query_gpt_judge(prompt)
return (verdict.lower() == "yes"), problem["id"]
def compute_accuracy(records):
correct = sum(1 for item in records if item.get("score"))
total = len(records)
return {"correct": correct, "total": total, "accuracy": correct / total if total else 0.0}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output_dir", type=str, default="./results")
parser.add_argument("--output_file", type=str, default="MMK12.json")
parser.add_argument("--response_label", type=str, default="response")
parser.add_argument("--number", type=int, default=-1)
parser.add_argument("--output_label", type=str, default="extract")
args = parser.parse_args()
input_path = os.path.join(args.output_dir, args.output_file)
print(f"Loading: {input_path}")
with open(input_path, "r") as f:
data = json.load(f)
ids_to_process = list(data.keys())
if args.number > 0:
ids_to_process = ids_to_process[:args.number]
print(f"Evaluating {len(ids_to_process)} samples...")
with ThreadPoolExecutor(max_workers=32) as executor:
futures = [
executor.submit(evaluate_sample, data[sid]) for sid in ids_to_process
]
for future in as_completed(futures):
result, pid = future.result()
data[pid]["score"] = result
# Save annotated results
output_path = input_path.replace(".json", f"_{args.output_label}.json")
with open(output_path, "w") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
print(f"Detailed results saved to {output_path}")
# Compute summary stats
results_list = list(data.values())
metrics = compute_accuracy(results_list)
print(metrics)
# Save accuracy
score_path = input_path.replace(".json", "_score.json")
with open(score_path, "w") as f:
json.dump(metrics, f, indent=4, ensure_ascii=False)
print(f"Accuracy summary saved to {score_path}")
+145
View File
@@ -0,0 +1,145 @@
import argparse
import json
import os
import random
import time
from tqdm import tqdm
from io import BytesIO
import base64
from concurrent.futures import ThreadPoolExecutor
def pil_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
from datasets import load_dataset
from qwen_vl_utils import process_vision_info
from transformers import AutoProcessor
from vllm import LLM, SamplingParams
from openai import OpenAI
import random
# Openai setting
openai_api_key = "kunlun"
hostname = "xxx"
openai_api_base = f"http://{hostname}:8000/v1"
client = OpenAI(api_key=openai_api_key, base_url=openai_api_base)
ds_collections = {
"MMK12": {
"root": "FanqingM/MMK12",
"split": "test",
}
}
SYSTEM_PROMPT_32B = "Solve the question. The user asks a question, and you solves it. You first thinks about the reasoning process in the mind and then provides the user with the answer. The answer is in latex format and wrapped in $...$. The final answer must be wrapped using the \\\\boxed{} command. Th answer should be enclosed within <answer> </answer> tags, i.e., Since $1+1=2$, so the answer is $2$. <answer> The answer is $\\\\boxed{2}$ </answer>, which means the final answer assistant's output should start with <answer> and end with </answer>."
SYSTEM_PROMPT_7B = "Solve the question. The user asks a question, and you solves it. You first thinks about the reasoning process in the mind and then provides the user with the answer. The answer is in latex format and wrapped in $...$. The final answer must be wrapped using the \\\\boxed{} command. The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., <think> Since $1+1=2$, so the answer is $2$. </think><answer> The answer is $\\\\boxed{2}$ </answer>, which means assistant's output should start with <think> and end with </answer>."
def vllm_inference(message):
max_retries = 2
retry_count = 0
timeout_seconds = 600
while retry_count < max_retries:
try:
chat_response = client.chat.completions.create(
model="r1v3-alpha",
max_tokens=16384,
temperature=0.8,
timeout=timeout_seconds,
messages=message
)
return {
"response": chat_response.choices[0].message.content,
"completion_token": chat_response.usage.completion_tokens,
"prompt_token": chat_response.usage.prompt_tokens,
}
except Exception as e:
retry_count += 1
print(f"Request failed (attempt {retry_count}/{max_retries}): {str(e)}")
if retry_count >= max_retries:
return {"response": f"Error after {max_retries} retries: {str(e)}", "reasoning_content": "", "completion_token": 0, "prompt_token": 0}
timeout_seconds += 30
def evaluate_chat_model():
random.seed(args.seed)
for ds_name in args.datasets:
data = load_dataset(ds_collections[ds_name]["root"], cache_dir=os.path.join(os.getcwd(), "data/MMK12/"))[
ds_collections[ds_name]["split"]
]
# data = data.select(range(5))
results_file = "MMK12_0618_fast_thinking_all_2k.json"
output_path = os.path.join(args.out_dir, results_file)
if os.path.exists(output_path):
with open(output_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
already_done_ids = set(existing_data.keys())
print(f"Already evaluated {already_done_ids} samples.")
print(f"Found {len(already_done_ids)} already evaluated samples.")
else:
existing_data = {}
already_done_ids = set()
messages = []
data_to_process = []
for data_item in tqdm(data, desc="Preparing messages"):
if str(data_item["id"]) in already_done_ids:
continue # 已经完成的样本跳过
data_item["query"] = data_item["question"]
image = data_item["image"]
message = [
{
"role": "system",
"content": [
{"type": "text", "text": SYSTEM_PROMPT_32B},
],
},
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{pil_to_base64(image)}"}},
{"type": "text", "text": data_item["query"]},
],
},
]
messages.append(message)
data_to_process.append(data_item)
if not messages:
print(f"All samples already processed for {ds_name}.")
continue
# 并发执行
with ThreadPoolExecutor(max_workers=256) as executor:
model_outputs = list(tqdm(executor.map(vllm_inference, messages), total=len(messages), desc="Parallel inference"))
# 把新推理结果更新进去
for data_item, model_output in zip(data_to_process, model_outputs):
del data_item["image"]
data_item["response"] = model_output["response"]
existing_data[str(data_item["id"])] = data_item
json.dump(existing_data, open(output_path, "w", encoding="utf-8"), indent=4, ensure_ascii=False)
print(f"Results saved to {output_path}")
cmd = f"python eval/mmk12/extract_calculate.py --output_file {results_file}"
print(cmd)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--datasets", type=str, default="MMK12")
parser.add_argument("--out-dir", type=str, default="results")
parser.add_argument("--seed", type=int, default=0)
args = parser.parse_args()
if not os.path.exists(args.out_dir):
os.makedirs(args.out_dir)
args.datasets = args.datasets.split(",")
print("datasets:", args.datasets)
evaluate_chat_model()
+4
View File
@@ -0,0 +1,4 @@
set -x
MODEL_PATH=/path/to/r1v3-model
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m vllm.entrypoints.openai.api_server --model $MODEL_PATH --port 8000 --trust-remote-code --max_model_len 32768 --served-model-name r1v3-alpha --limit-mm-per-prompt "image=60" --gpu_memory_utilization 0.8 --tensor-parallel-size 8 --dtype auto
+43
View File
@@ -0,0 +1,43 @@
# 🧪 Evaluation
We provide evaluation scripts to reproduce the results of **Skywork R1V3**.
Most benchmarks can be evaluated using **[VLMEvalKit](https://github.com/open-compass/VLMEvalKit)**, except for [EMMA-mini](https://github.com/EMMA-Bench/EMMA) and [MMK12](https://github.com/ModalMinds/MM-EUREKA).
---
### Environment Setup
```bash
bash ./eval/vlmevalkit/build_env.sh
```
### Set OpenAI API Key and Base URL
Create or edit the `.env` file in `vlmevalkit/` and add the following:
```dotenv
OPENAI_API_KEY=your_api_key_here
OPENAI_API_BASE=https://your_base_url_here
```
# 🚀 Evaluation Steps
**Step 1: Launch the Model**
Start tmux and deploy the model
```bash
tmux
export TORCH_CUDA_ARCH_LIST="8.9+PTX"
bash ./vlmevalkit/eval_shell/launch_vlm.sh
```
**Step 2: Run Evaluation Scripts**
Evaluate on supported benchmarks:
```bash
bash ./vlmevalkit/eval_shell/run_eval.sh
```
> ⚠️ **Note:** Some benchmarks (e.g., `MMMU`) require post-processing to adjust results using rule-based scripts.
# 📌 Additional Notes
- Ensure the model is properly loaded before running evaluation.
- All results will be saved under the `outputs/` directory.
- For MMK12 and EMMA-mini, please refer to their individual README files for evaluation instructions.
+61
View File
@@ -0,0 +1,61 @@
import argparse
import ast
import json
import os
import pandas as pd
def validate_scores(dataset_list, assert_score, model_name):
for dataset in dataset_list:
base_score = assert_score[dataset][model_name]
if dataset == "OCRBench_MINI":
score_file = os.path.join("outputs", f"{model_name}/{model_name}_{dataset}_score.json")
cur_score = 0
with open(score_file, "r") as f:
total_score = json.load(f)
cur_score = total_score["Final Score Norm"]
assert (
abs(cur_score - float(base_score)) <= 0.01
), f"{dataset} on {model_name}: cur_score is {cur_score}, base_score is {base_score}"
else:
score_file = os.path.join("outputs", f"{model_name}/{model_name}_{dataset}_acc.csv")
df = pd.read_csv(score_file)
cur_score = df["Overall"].iloc[0]
if dataset == "MMBench_V11_MINI":
cur_score = df.loc[df["split"] == "dev", "Overall"].values
assert (
abs(cur_score - float(base_score)) <= 0.01
), f"{dataset} on {model_name}: cur_score is {cur_score}, base_score is {base_score}"
print(f"cur_score is {cur_score}, base_score is {base_score}")
def parse_arguments():
parser = argparse.ArgumentParser(description="Validate model scores against csv/json data")
parser.add_argument("--dataset", type=str, required=True, help="Space-separated list of datasets")
parser.add_argument(
"--base_score", type=str, required=True, help="Dictionary string in format {dataset:{model:score}}"
)
parser.add_argument("--model-name", type=str, required=True, help="Name of the model to validate")
return parser.parse_args()
def main():
args = parse_arguments()
try:
dataset_list = args.dataset.split()
base_score = ast.literal_eval(args.base_score)
except Exception as e:
print(f"Parameter parsing error: {str(e)}")
return
validate_scores(dataset_list, base_score, args.model_name)
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
name: lint
on: [push, pull_request]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python 3.10
uses: actions/setup-python@v2
with:
python-version: 3.10.15
- name: Install pre-commit hook
run: |
pip install pre-commit
pre-commit install
- name: Linting
run: pre-commit run --all-files
+47
View File
@@ -0,0 +1,47 @@
name: pr_run_test
on:
pull_request:
branches:
- "main"
paths-ignore:
- "docs/**"
- "**.md"
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
env:
BASE_SCORE: '{"MMBench_V11_MINI":{"Qwen2-VL-7B-Instruct":0.8727272727272727,"InternVL2_5-8B":0.8727272727272727,"llava_onevision_qwen2_7b_si":0.8363636363636363},"MMStar_MINI":{"Qwen2-VL-7B-Instruct":0.6266666666666667,"InternVL2_5-8B":0.6333333333333333,"llava_onevision_qwen2_7b_si":0.49333333333333335},"AI2D_MINI":{"Qwen2-VL-7B-Instruct":0.7854251012145749,"InternVL2_5-8B":0.8421052631578947,"llava_onevision_qwen2_7b_si":0.8178137651821862},"OCRBench_MINI":{"Qwen2-VL-7B-Instruct":16.6,"InternVL2_5-8B":16.4,"llava_onevision_qwen2_7b_si":12.9}}'
jobs:
vlm_test:
if: ${{!cancelled()}}
runs-on: [linux-a100]
strategy:
fail-fast: false
matrix:
model: [Qwen/Qwen2-VL-7B-Instruct,OpenGVLab/InternVL2_5-8B,lmms-lab/llava-onevision-qwen2-7b-si]
dataset: ["MMBench_V11_MINI MMStar_MINI AI2D_MINI","OCRBench_MINI"]
container:
image: kkscilife/vlmevalkit_2:a100
options: "--gpus=all --ipc=host -e https_proxy=$https_proxy -e http_proxy=$http_proxy --pull never"
volumes:
- /mnt/187:/mnt/187
steps:
- name: clone_repo
uses: actions/checkout@v3
- name: evaluation_model
run: |
pip install -e .
pre_model=$(echo ${{matrix.model}} | awk -F'/' '{print $1}')
ln -s /mnt/187/$pre_model .
if [ "${{matrix.model}}" = "lmms-lab/llava-onevision-qwen2-7b-si" ];then
model_name="llava_onevision_qwen2_7b_si"
else
model_name=$(echo ${{matrix.model}} | awk -F'/' '{print $2}')
fi
nvidia-smi
python run.py --data ${{matrix.dataset}} --model $model_name
python .github/scripts/assert_score.py --dataset "${{matrix.dataset}}" --base_score $BASE_SCORE --model-name $model_name
+203
View File
@@ -0,0 +1,203 @@
.idea/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
.vscode/
.gradio/
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# Images
images/
scripts/*ttf
.history
cache_dir/*
# Evaluation Outputs
outputs/*
demo.ipynb
*json
!vlmeval/dataset/utils/vgrpbench/configs/formating-prompt/**/*.json
.vscode
*.swp
GPT4o_MINI/
2weiyun*
script.py
Gemini*
Claude3-5V*
GLM4V*
GPT4o*
GPT4V*
mmmu_debug
bailingMM
BailingMM*
SenseChat*
Step*
DoubaoVL
arch
BlueLM*
mmb_*
gpt-4.1*
Reka*
Taiyi
TeleMM
apple.jpg
assets/LOGO.png
api_list.txt
vlmeval/gemini_tmp.py
run.sh
run_g.sh
tmp/
InternVL*
Qwen*
+41
View File
@@ -0,0 +1,41 @@
exclude: |
(?x)^(
scripts/|
assets/|
vlmeval/config.py |
vlmeval/dataset/utils/wemath.py |
vlmeval/dataset/Omnidocbench/ |
vlmeval/dataset/utils/megabench/ |
vlmeval/dataset/utils/vgrpbench/ |
vlmeval/vlm/ola/ |
vlmeval/vlm/ursa/ |
vlmeval/vlm/ovis/
)
repos:
- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
args:
[
"--max-line-length=120",
"--ignore=F401,F403,F405,E402,E722,E741,W503,E231,E702",
]
exclude: ^configs/
- repo: https://github.com/pre-commit/mirrors-yapf
rev: v0.30.0
hooks:
- id: yapf
args: ["--style={column_limit=120}"]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.1.0
hooks:
- id: trailing-whitespace
- id: check-yaml
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: check-merge-conflict
- id: fix-encoding-pragma
args: ["--remove"]
- id: mixed-line-ending
args: ["--fix=lf"]
+203
View File
@@ -0,0 +1,203 @@
Copyright 2023 VLMEvalKit Authors. All rights reserved.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2023 VLMEvalKit Authors.
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.
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1920" height="480" viewBox="0 0 1920 480" xml:space="preserve">
<desc>Created with Fabric.js 5.3.0</desc>
<defs>
</defs>
<g transform="matrix(8.6096948697 0 0 8.6096948697 283.4607944077 326.096948697)" id="2rbaYufxVtcDPCyBcyhLL" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(88,120,180); fill-rule: nonzero; opacity: 1;" transform=" translate(-19.1, -28)" d="M 16.5 22.6 L 10.1 25.700000000000003 L 15.399999999999999 25.500000000000004 L 16.5 22.6 z M 12.3 33.6 L 13.4 30.700000000000003 L 8.100000000000001 30.900000000000002 L 12.3 33.6 z M 21.6 33.3 L 28 30.199999999999996 L 22.7 30.399999999999995 L 21.6 33.3 z M 25.8 22.4 L 24.7 25.299999999999997 L 30 25.099999999999998 L 25.8 22.4 z M 31.5 26.2 L 24.4 26.4 L 22.7 25.299999999999997 L 24.2 21.299999999999997 L 22.2 20 L 19 21.5 L 17.5 25.4 L 14.8 26.7 L 7.700000000000001 26.9 L 4.500000000000001 28.4 L 6.600000000000001 29.799999999999997 L 13.700000000000001 29.599999999999998 L 13.700000000000001 29.599999999999998 L 15.4 30.7 L 13.9 34.7 L 16 36 L 19.2 34.5 L 20.7 30.6 L 20.7 30.6 L 23.3 29.400000000000002 L 23.3 29.400000000000002 L 30.5 29.200000000000003 L 33.7 27.700000000000003 L 31.5 26.2 z M 20.2 28.7 C 19.2 29.2 17.9 29.2 17.2 28.8 C 16.599999999999998 28.400000000000002 16.8 27.6 17.8 27.2 C 18.8 26.7 20.1 26.7 20.8 27.099999999999998 C 21.5 27.5 21.2 28.2 20.2 28.7 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 351.9078686218 195.2295866776)" id="Gj0NH9qgtM_hm6hdZ_Tf1" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(54,86,155); fill-rule: nonzero; opacity: 1;" transform=" translate(-27.05, -12.8)" d="M 33.5 19.8 L 32.2 13.3 L 30.700000000000003 15.200000000000001 L 33.5 19.8 z M 27.5 5.1 L 23.3 2.3999999999999995 L 26 7 L 27.5 5.1 z M 20.7 5.7 L 22 12.2 L 23.5 10.299999999999999 L 20.7 5.7 z M 26.8 20.4 L 31 23.099999999999998 L 28.3 18.5 L 26.8 20.4 z M 34 22.3 L 30.4 16.1 L 30.4 16.1 L 29.9 13.400000000000002 L 31.9 10.800000000000002 L 31.299999999999997 7.600000000000002 L 29.199999999999996 6.200000000000003 L 27.199999999999996 8.800000000000002 L 25.499999999999996 7.700000000000003 L 21.799999999999997 1.400000000000003 L 19.6 0 L 20.200000000000003 3.2 L 23.900000000000002 9.5 L 23.900000000000002 9.5 L 24.400000000000002 12.1 L 24.400000000000002 12.1 L 22.400000000000002 14.7 L 23.000000000000004 17.9 L 25.100000000000005 19.299999999999997 L 27.000000000000004 16.799999999999997 L 28.700000000000003 17.9 L 32.400000000000006 24.2 L 34.50000000000001 25.599999999999998 L 34 22.3 z M 27.5 14.6 C 26.9 14.2 26.2 13 26 12 C 25.8 11 26.2 10.5 26.8 10.9 C 27.400000000000002 11.3 28.1 12.5 28.3 13.5 C 28.5 14.6 28.1 15.1 27.5 14.6 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 209.8479032717 200.3954035994)" id="lmxdEhRpowSXVKC1LScVi" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1;" transform=" translate(-10.55, -13.4)" d="M 12 2.8 L 5.6 5.9 L 9.399999999999999 7.6000000000000005 L 12 2.8 z M 1.1 14.4 L 2.4000000000000004 20.9 L 5 16.099999999999998 L 1.1 14.4 z M 9.1 24 L 15.5 20.9 L 11.7 19.2 L 9.1 24 z M 20 12.4 L 18.7 5.9 L 16.099999999999998 10.7 L 20 12.4 z M 20.4 14.9 L 15.299999999999999 12.600000000000001 L 15.299999999999999 12.600000000000001 L 14.799999999999999 9.900000000000002 L 18.299999999999997 3.400000000000002 L 17.699999999999996 0.20000000000000195 L 14.499999999999996 1.700000000000002 L 11 8.1 L 8.3 9.4 L 8.3 9.4 L 3.2 7.1 L 0 8.6 L 0.6 11.8 L 5.8 14.100000000000001 L 6.3 16.8 L 6.3 16.8 L 2.8 23.4 L 3.4 26.599999999999998 L 6.6 25.099999999999998 L 10.1 18.599999999999998 L 12.7 17.4 L 12.7 17.4 L 17.9 19.799999999999997 L 21.099999999999998 18.299999999999997 L 20.4 14.9 z M 10.9 15.2 C 9.9 15.7 9 15.2 8.8 14.2 C 8.600000000000001 13.2 9.200000000000001 12 10.200000000000001 11.5 C 11.200000000000001 11 12.100000000000001 11.5 12.3 12.5 C 12.5 13.5 11.9 14.7 10.9 15.2 z" stroke-linecap="round" />
</g>
<g transform="matrix(1 0 0 1 1109.6072390741 240)" style="" id="IiDed4ej1oioRNDwSqAwf">
<text xml:space="preserve" font-family="Amethysta" font-size="225" font-style="normal" font-weight="normal" line-height="1" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1; white-space: pre;"><tspan x="-714.0188713264" y="72.3065" style="white-space: pre; "> VLMEvalKit</tspan></text>
<style>
@font-face {
font-family: "Amethysta";
font-weight: normal;
src: url("data:font/ttf;base64,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 truncated
}
</style></g></svg>

After

Width:  |  Height:  |  Size: 87 KiB

+5
View File
@@ -0,0 +1,5 @@
pip install -r ./eval/vlmevalkit/requirements.txt -i https://mirrors.bfsu.edu.cn/pypi/web/simple
pip install vllm==0.8.3 -i https://mirrors.bfsu.edu.cn/pypi/web/simple
export TORCH_CUDA_ARCH_LIST="8.9+PTX"
pip install -U torchao -i https://mirrors.bfsu.edu.cn/pypi/web/simple
apt-get update && apt-get install libgl1
View File
Whitespace-only changes.
+17
View File
@@ -0,0 +1,17 @@
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.8"
formats:
- epub
sphinx:
configuration: docs/en/conf.py
python:
install:
- requirements: requirements/docs.txt
+67
View File
@@ -0,0 +1,67 @@
# Config System
By default, VLMEvalKit launches the evaluation by setting the model name(s) (defined in `/vlmeval/config.py`) and dataset name(s) (defined in `vlmeval/dataset/__init__.py` or `vlmeval/dataset/video_dataset_config.py`) in the `run.py` script with the `--model` and `--data` arguments. Such approach is simple and efficient in most scenarios, however, it may not be flexible enough when the user wants to evaluate multiple models / datasets with different settings.
To address this, VLMEvalKit provides a more flexible config system. The user can specify the model and dataset settings in a json file, and pass the path to the config file to the `run.py` script with the `--config` argument. Here is a sample config json:
```json
{
"model": {
"GPT4o_20240806_T00_HIGH": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 0,
"img_detail": "high"
},
"GPT4o_20240806_T10_Low": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 1.0,
"img_detail": "low"
},
"GPT4o_20241120": {}
},
"data": {
"MME-RealWorld-Lite": {
"class": "MMERealWorld",
"dataset": "MME-RealWorld-Lite"
},
"MMBench_DEV_EN_V11": {
"class": "ImageMCQDataset",
"dataset": "MMBench_DEV_EN_V11"
},
"MMBench_Video_8frame_nopack":{},
"Video-MME_16frame_subs": {
"class": "VideoMME",
"dataset": "Video-MME",
"nframe": 16,
"use_subtitle": true
}
}
}
```
Explanation of the config json:
1. Now we support two fields: `model` and `data`, each of which is a dictionary. The key of the dictionary is the name of the model / dataset (set by the user), and the value is the setting of the model / dataset.
2. For items in `model`, the value is a dictionary containing the following keys:
- `class`: The class name of the model, which should be a class name defined in `vlmeval/vlm/__init__.py` (open-source models) or `vlmeval/api/__init__.py` (API models).
- Other kwargs: Other kwargs are model-specific parameters, please refer to the definition of the model class for detailed usage. For example, `model`, `temperature`, `img_detail` are arguments of the `GPT4V` class. It's noteworthy that the `model` argument is required by most model classes.
- Tip: The defined model in the `supported_VLM` of `vlmeval/config.py` can be used as a shortcut, for example, `GPT4o_20241120: {}` is equivalent to `GPT4o_20241120: {'class': 'GPT4V', 'model': 'gpt-4o-2024-11-20', 'temperature': 0, 'img_size': -1, 'img_detail': 'high', 'retry': 10, 'verbose': False}`
3. For the dictionary `data`, we suggest users to use the official dataset name as the key (or part of the key), since we frequently determine the post-processing / judging settings based on the dataset name. For items in `data`, the value is a dictionary containing the following keys:
- `class`: The class name of the dataset, which should be a class name defined in `vlmeval/dataset/__init__.py`.
- Other kwargs: Other kwargs are dataset-specific parameters, please refer to the definition of the dataset class for detailed usage. Typically, the `dataset` argument is required by most dataset classes. It's noteworthy that the `nframe` argument or `fps` argument is required by most video dataset classes.
- Tip: The defined dataset in the `supported_video_datasets` of `vlmeval/dataset/video_dataset_config.py` can be used as a shortcut, for example, `MMBench_Video_8frame_nopack: {}` is equivalent to `MMBench_Video_8frame_nopack: {'class': 'MMBenchVideo', 'dataset': 'MMBench-Video', 'nframe': 8, 'pack': False}`.
Saving the example config json to `config.json`, you can launch the evaluation by:
```bash
python run.py --config config.json
```
That will generate the following output files under the working directory `$WORK_DIR` (Following the format `{$WORK_DIR}/{$MODEL_NAME}/{$MODEL_NAME}_{$DATASET_NAME}_*`):
- `$WORK_DIR/GPT4o_20240806_T00_HIGH/GPT4o_20240806_T00_HIGH_MME-RealWorld-Lite*`
- `$WORK_DIR/GPT4o_20240806_T10_Low/GPT4o_20240806_T10_Low_MME-RealWorld-Lite*`
- `$WORK_DIR/GPT4o_20240806_T00_HIGH/GPT4o_20240806_T00_HIGH_MMBench_DEV_EN_V11*`
- `$WORK_DIR/GPT4o_20240806_T10_Low/GPT4o_20240806_T10_Low_MMBench_DEV_EN_V11*`
...
+21
View File
@@ -0,0 +1,21 @@
# Contributors
## Contributors w. 3+ Major Contributions
> In this section, we list all the contributors who have made significant contributions (3+) to the development of VLMEvalKit.
New Qualified Contributors (2024.09):
1. [amitbcp](https://github.com/amitbcp): The contributor helped support MUIRBench, Phi-3.5, Idefics3, VILA, and xGen-MM
2. [czczup](https://github.com/czczup): The contributor helped support the InternVL Series (V1.5, Mini-InternVL, V2, etc.)
3. [DseidLi](https://github.com/DseidLi): The contributor helped support LLaVA-OneVision, GQA, and developed the readthedocs site for VLMEvalKit
4. [mayubo2333](https://github.com/mayubo2333): The contributor helped support MMLongBench, SlideVQA, and DUDE
5. [sun-hailong](https://github.com/sun-hailong): The contributor helped support A-OKVQA, Parrot, MMMB, and MTL-MMBench
6. [PhoenixZ810](https://github.com/PhoenixZ810): The contributor helped support Video-ChatGPT, Chat-UniVI, and Llama-VID
7. [Cuiunbo](https://github.com/Cuiunbo): The contributor helped support OmniLMM-12B, MiniCPM-V Series (V1, V2, V2.5)
## Full Contributor List
> In this section, we list all the contributors as well as their corresponding contributions to the development of VLMEvalKit.
TBD.
+145
View File
@@ -0,0 +1,145 @@
# Develop new Benchmark / MLLM
> 🛠️ How to implement a new Benchmark / VLM in VLMEvalKit?
## Implement a new benchmark
Example PR: **Math-Vision Benchmark** ([#292](https://github.com/open-compass/VLMEvalKit/pull/292/files))
In VLMEvalKit, benchmarks are organized as dataset classes. When you try to implement a new benchmark, you can either reuse existing dataset classes (*e.g.*, You can reuse `ImageMCQDataset` when implementing a new multi-choice benchmark), or support a new dataset class. Each dataset must have the following two member functions (either reuse the one of the parent class or implement your own):
- `build_prompt(self, line)`: The function input `line` is an integer (the sample index) or a `pd.Series` object (the raw record of the sample). The function outputs a `multi-modal message`, serving as the input of an MLLM. The `multi-modal message` is an interleaved list of multi-modal messages adopting the following format (the example includes an image and a text message): `[dict(type='image', value=IMAGE_PTH), dict(type='text', value=prompt)]`.
- `evaluate(self, eval_file, **judge_kwargs)`: The function input `eval_file` is the MLLM prediction (typically in `.xlsx` format). If the benchmark requires an external LLM (typically GPT) for evaluation, then `judge_kwargs` can pass the arguments for the LLM. The function outputs the benchmark evaluation results (metrics) in the form of `dict` or `pd.DataFrame`.
We then brief the typical steps to implement a new benchmark under VLMEvalKit:
### 1. Prepare your benchmark tsv file
Currently, we organize a benchmark as one single TSV file. During inference, the data file will be automatically downloaded from the definited `DATASET_URL` link to `$LMUData` file (default path is `$HOME/LMUData`, if not set explicitly). You can upload the prepared TSV file to a downloadable address (e.g., Huggingface) or send it to us at <opencompass@pjlab.org.cn>. We will assist in uploading the dataset to the server. You can also customize `LMUData` path in the environment variable `LMUData=/path/to/your/data`.
The contents of the TSV file consist of:
| Dataset Name \ Fields | index | image | image_path | question | hint | multi-choice<br>options | answer | category | l2-category | split |
| --------------------------------------- | ----- | ----- | ---------- | -------- | ---- | ----------------------- | ------ | -------- | ----------- | ----- |
| MMBench_DEV_[CN/EN] | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| MMBench_TEST_[CN/EN] | ✅ | ✅ | | ✅ | ✅ | ✅ | | ✅ | ✅ | ✅ |
| CCBench | ✅ | ✅ | | ✅ | | ✅ | ✅ | ✅ | | |
| SEEDBench_IMG | ✅ | ✅ | | ✅ | | ✅ | ✅ | ✅ | | |
| MME | ✅ | ✅ | | ✅ | | | ✅ | ✅ | | |
| MMVet | ✅ | ✅ | | ✅ | | | ✅ | ✅ | | |
| MMMU_DEV_VAL | ✅ | ✅ | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |
| COCO_VAL | ✅ | ✅ | | | | | ✅ | | | |
| OCRVQA_[TEST/TESTCORE] | ✅ | ✅ | | ✅ | | | ✅ | | | |
| TextVQA_VAL | ✅ | ✅ | | ✅ | | | ✅ | | | |
| VCR_[EN/ZH]\_[EASY/HARD]\_[ALL/500/100] | ✅ | ✅ | | ✅ | | | ✅ | | | |
| MMMB_[en/cn/pt/ar/tr/ru] | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ | |✅ |
| MMBench_dev_[en/cn/pt/ar/tr/ru] | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |✅ |
<div align="center"><b>Table 1. TSV fields of supported datasets.</b></div>
**Intro to mandatory fields in the `TSV` file:**
- **index:** Integer, Unique for each line in `tsv`
- **image:** The base64 of the image, you can use APIs implemented in `vlmeval/smp/vlm.py` for encoding and decoding:
- Encoding: `encode_image_to_base64 `(for PIL Image) / `encode_image_file_to_base64` (for image file path)
- Decoding: `decode_base64_to_image`(for PIL Image) / `decode_base64_to_image_file` (for image file path)
- **question**: The question corresponding to the image, a string
- **answer**: The answer to the question, a string. The `test` split does not need this field
### 2. Cutomize your benchmark prompt
`ImageBaseDataset` defines the default prompt format. If you need to add prompts specific to the dataset or input data in the `Interleave` format to the model, you can implement this through the `build_prompt(line)` function. This function takes a line from a TSV file as input, containing fields such as index, image, question, etc. The function returns a dictionary list of multimodal messages `msg` in the format `[dict(type='image', value=IMAGE_PTH), dict(type='text', value=prompt)]`, including the image path and the text prompt to be input into VLMs. For interleave type inputs, you can directly place the dictionary of the image path at the image token position.
### 3. Cutomize your benchmark metrics
To add evaluation for a new benchmark, you need to customize a class object to implement the dataset’s metrics calculation. Multimodal datasets inherit from the `ImageBaseDataset` object in `vlmeval/dataset/image_base.py`. The TYPE defines the type of dataset, `DATASET_URL` is the download address of the dataset, and `DATASET_MD5` is the MD5 checksum for consistency checking of the dataset file.
In this class, **you need to implement** the `evaluate(eval_file, **judge_kwargs)` class function to calculate metrics and output results for the custom dataset. The function input `eval_file` is the path to the model prediction results file `{model_name}_{dataset}.xlsx`. This file can be read as a pandas.DataFrame using the `load(eval_file)` method, containing fields such as index, question, answer, category, prediction, etc. The judge_kwargs will pass a dictionary related to evaluation, such as the name of the `judge model`, the number of API request threads, etc. **The return value** of the function is the calculated accuracy and other metrics, formatted as a dictionary composed of lists, organized into a pandas.DataFrame.
## Implement a new model
Example PR: **Support LLaVA-Next-Interleave** ([#294](https://github.com/open-compass/VLMEvalKit/pull/294))
**1. Support `generate_inner` API (mandatory).**
All existing models are implemented in `vlmeval/vlm`. For a minimal model, your model class **must implement the method** `generate_inner(msgs, dataset=None)`. In this function, you feed a multi-modal message to your VLM and return the VLM prediction (which is a string). The optional argument `dataset` can be used as the flag for the model to switch among various inference strategies.
The multi-modal messages `msgs` is a list of dictionaries, each dictionary has two keys: type and value:
- `type`: We currently support two types, choices are ["image", "text"].
- `value`: When type=='text' , the value is the text message (a single string); when type=='image', the value can be the local path of an image file, or the image URL.
Currently a multi-modal message may contain arbitrarily interleaved images and texts. If your model do not support that, a practice can be taking the 1st image and concatenated text messages as the input. You can set the `INTERLEAVE = False` in your model class and use `self.message_to_promptimg(message, dataset=dataset)` to build your prompt and the first image's path.
Here are some examples of multi-modal messages:
```python
IMAGE_PTH = 'assets/apple.jpg'
IMAGE_URL = 'https://raw.githubusercontent.com/open-compass/VLMEvalKit/main/assets/apple.jpg'
msg1 = [
dict(type='image', value=IMAGE_PTH),
dict(type='text', value='What is in this image?')
]
msg2 = [
dict(type='image', value=IMAGE_URL),
dict(type='image', value=IMAGE_URL),
dict(type='text', value='How many apples are there in these images?')
]
response = model.generate(msg1)
```
For convenience sake, we also support to take a list of string as inputs. In that case, we will check if a string is an image path or image URL and automatically convert it to the list[dict] format:
```python
IMAGE_PTH = 'assets/apple.jpg'
IMAGE_URL = 'https://raw.githubusercontent.com/open-compass/VLMEvalKit/main/assets/apple.jpg'
msg1 = [IMAGE_PTH, 'What is in this image?']
msg2 = [IMAGE_URL, IMAGE_URL, 'How many apples are there in these images?']
response = model.generate(msg1)
```
**Support Custom Prompt (optional).**
Besides, your model can support **custom prompt building** by implementing two optional methods: `use_custom_prompt(dataset)` and `build_prompt(line, dataset=None)`.
Both functions take the dataset name as the input:
- `use_custom_prompt(dataset)` returns a boolean flag, indicating whether the model should use the custom prompt building strategy.
- If `use_custom_prompt(dataset)` returns True, `build_prompt(line, dataset)` should return a customly bulit multimodal message for the corresponding `dataset`, given `line`, which is a dictionary that includes the necessary information of a data sample. If `use_custom_prompt(dataset)` returns False, the default prompt building strategy will be used.
**Support multi-turn chatting (optional).**
You can also support the multi-turn chatting and evaluation with your VLM by supporting the `chat_inner(message, dataset)` function. The function outputs a single string response, and the `message` is a list of chat history, following the below format.
```python
# Assume msg1, msg2, msg3, ... are multi-modal messages following the previously described format
# `chat_inner` take the following chat history list as input:
message = [
dict(role='user', content=msg1),
dict(role='assistant', content=msg2),
dict(role='user', content=msg3),
dict(role='assistant', content=msg4),
......
dict(role='user', content=msgn),
]
# `message` should contain an odd number of chat utterances, the role of utterances should be interleaved "user" and "assistant", with the role of the last utterance to be "user".
# The chat function will call `chat_inner`
response = model.chat(message)
```
### Example PRs:
- VLM that doesn't support interleaved images and texts, and does not use custom prompts: [[Model] Support glm-4v-9b](https://github.com/open-compass/VLMEvalKit/pull/221)
- VLM that supports interleaved images and texts and custom prompts: [Add MiniCPM-Llama3-V-2.5](https://github.com/open-compass/VLMEvalKit/pull/205)
- VLM API: [Feature add glmv](https://github.com/open-compass/VLMEvalKit/pull/201)
## Contribute to VLMEvalKit
If you want to contribute codes to **VLMEvalKit**, please do the pre-commit check before you submit a PR. That helps to keep the code tidy.
```bash
# Under the directory of VLMEvalKit, install the pre-commit hook:
pip install pre-commit
pre-commit install
pre-commit run --all-files
# Then you can commit your code.
```
+27
View File
@@ -0,0 +1,27 @@
# Using LMDeploy to Accelerate Evaluation and Inference
VLMEvalKit supports testing VLM models deployed by LMDeploy. Below, we use InternVL2-8B as an example to show how to test the model.
## Step 0: Install LMDeploy
```bash
pip install lmdeploy
```
For other installation methods, you can refer to LMDeploy's [documentation](https://github.com/InternLM/lmdeploy).
## Step 1: Start the Inference Service
```bash
lmdeploy serve api_server OpenGVLab/InternVL2-8B --model-name InternVL2-8B
```
> [!IMPORTANT]
> Since models in VLMEvalKit may have custom behaviors when building prompts for different datasets, such as InternVL2's handling of HallusionBench, it is necessary to specify `--model-name` when starting the server. This allows the VLMEvalKit to select appropriate prompt construction strategy based on the name when using the LMDeploy API.
>
> If `--server-port`, is specified, the corresponding environment variable `LMDEPLOY_API_BASE` needs to be set.
## Step 2: Evaluation
```bash
python run.py --data MMStar --model lmdeploy --verbose --api-nproc 64
```
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+221
View File
@@ -0,0 +1,221 @@
# Quickstart
Before running the evaluation script, you need to **configure** the VLMs and set the model_paths properly.
After that, you can use a single script `run.py` to inference and evaluate multiple VLMs and benchmarks at a same time.
## Step 0. Installation & Setup essential keys
**Installation.**
```bash
git clone https://github.com/open-compass/VLMEvalKit.git
cd VLMEvalKit
pip install -e .
```
**Setup Keys.**
To infer with API models (GPT-4v, Gemini-Pro-V, etc.) or use LLM APIs as the **judge or choice extractor**, you need to first setup API keys. VLMEvalKit will use an judge **LLM** to extract answer from the output if you set the key, otherwise it uses the **exact matching** mode (find "Yes", "No", "A", "B", "C"... in the output strings). **The exact matching can only be applied to the Yes-or-No tasks and the Multi-choice tasks.**
- You can place the required keys in `$VLMEvalKit/.env` or directly set them as the environment variable. If you choose to create a `.env` file, its content will look like:
```bash
# The .env file, place it under $VLMEvalKit
# API Keys of Proprietary VLMs
# QwenVL APIs
DASHSCOPE_API_KEY=
# Gemini w. Google Cloud Backends
GOOGLE_API_KEY=
# OpenAI API
OPENAI_API_KEY=
OPENAI_API_BASE=
# StepAI API
STEPAI_API_KEY=
# REKA API
REKA_API_KEY=
# GLMV API
GLMV_API_KEY=
# CongRong API
CW_API_BASE=
CW_API_KEY=
# SenseNova API
SENSENOVA_API_KEY=
# Hunyuan-Vision API
HUNYUAN_SECRET_KEY=
HUNYUAN_SECRET_ID=
# LMDeploy API
LMDEPLOY_API_BASE=
# You can also set a proxy for calling api models during the evaluation stage
EVAL_PROXY=
```
- Fill the blanks with your API keys (if necessary). Those API keys will be automatically loaded when doing the inference and evaluation.
## Step 1. Configuration
**VLM Configuration**: All VLMs are configured in `vlmeval/config.py`. Few legacy VLMs (like MiniGPT-4, LLaVA-v1-7B) requires additional configuration (configuring the code / model_weight root in the config file). During evaluation, you should use the model name specified in `supported_VLM` in `vlmeval/config.py` to select the VLM. Make sure you can successfully infer with the VLM before starting the evaluation with the following command `vlmutil check {MODEL_NAME}`.
## Step 2. Evaluation
**New!!!** We integrated a new config system to enable more flexible evaluation settings. Check the [Document](/docs/en/ConfigSystem.md) or run `python run.py --help` for more details 🔥🔥🔥
We use `run.py` for evaluation. To use the script, you can use `$VLMEvalKit/run.py` or create a soft-link of the script (to use the script anywhere):
**Arguments**
- `--data (list[str])`: Set the dataset names that are supported in VLMEvalKit (names can be found in the codebase README).
- `--model (list[str])`: Set the VLM names that are supported in VLMEvalKit (defined in `supported_VLM` in `vlmeval/config.py`).
- `--mode (str, default to 'all', choices are ['all', 'infer'])`: When `mode` set to "all", will perform both inference and evaluation; when set to "infer", will only perform the inference.
- `--api-nproc (int, default to 4)`: The number of threads for OpenAI API calling.
- `--work-dir (str, default to '.')`: The directory to save evaluation results.
**Command for Evaluating Image Benchmarks **
You can run the script with `python` or `torchrun`:
```bash
# When running with `python`, only one VLM instance is instantiated, and it might use multiple GPUs (depending on its default behavior).
# That is recommended for evaluating very large VLMs (like IDEFICS-80B-Instruct).
# IDEFICS-80B-Instruct on MMBench_DEV_EN, MME, and SEEDBench_IMG, Inference and Evalution
python run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct --verbose
# IDEFICS-80B-Instruct on MMBench_DEV_EN, MME, and SEEDBench_IMG, Inference only
python run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct --verbose --mode infer
# When running with `torchrun`, one VLM instance is instantiated on each GPU. It can speed up the inference.
# However, that is only suitable for VLMs that consume small amounts of GPU memory.
# IDEFICS-9B-Instruct, Qwen-VL-Chat, mPLUG-Owl2 on MMBench_DEV_EN, MME, and SEEDBench_IMG. On a node with 8 GPU. Inference and Evaluation.
torchrun --nproc-per-node=8 run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct qwen_chat mPLUG-Owl2 --verbose
# Qwen-VL-Chat on MME. On a node with 2 GPU. Inference and Evaluation.
torchrun --nproc-per-node=2 run.py --data MME --model qwen_chat --verbose
```
**Command for Evaluating Video Benchmarks**
```bash
# When running with `python`, only one VLM instance is instantiated, and it might use multiple GPUs (depending on its default behavior).
# That is recommended for evaluating very large VLMs (like IDEFICS-80B-Instruct).
# IDEFICS2-8B on MMBench-Video, with 8 frames as inputs and vanilla evaluation. On a node with 8 GPUs. MMBench_Video_8frame_nopack is a defined dataset setting in `vlmeval/dataset/video_dataset_config.py`.
torchrun --nproc-per-node=8 run.py --data MMBench_Video_8frame_nopack --model idefics2_8
# GPT-4o (API model) on MMBench-Video, with 1 frame per second as inputs and pack evaluation (all questions of a video in a single query).
python run.py --data MMBench_Video_1fps_pack --model GPT4o
```
The evaluation results will be printed as logs, besides. **Result Files** will also be generated in the directory `$YOUR_WORKING_DIRECTORY/{model_name}`. Files ending with `.csv` contain the evaluated metrics.
### Frequently Asked Questions
#### Constructing Input Prompt: The `build_prompt()` Function
If you find that the model's output does not match the expected results when evaluating a specific benchmark, it could be due to the model not constructing the input prompt correctly.
In VLMEvalKit, each `dataset` class includes a function named `build_prompt()`, which is responsible for formatting input questions. Different benchmarks can either customize their own `build_prompt()` function or use the default implementation.
For instance, when handling the default [Multiple-Choice QA](https://github.com/open-compass/VLMEvalKit/blob/43af13e052de6805a8b08cd04aed5e0d74f82ff5/vlmeval/dataset/image_mcq.py#L164), the `ImageMCQDataset.build_prompt()` method combines elements such as `hint`, `question`, and `options` (if present in the dataset) into a complete question format, as shown below:
```
HINT
QUESTION
Options:
A. Option A
B. Option B
···
Please select the correct answer from the options above.
```
Additionally, since different models may have varying evaluation requirements, VLMEvalKit also supports customizing the prompt construction method at the model level through `model.build_prompt()`. For an example, you can refer to [InternVL](https://github.com/open-compass/VLMEvalKit/blob/43af13e052de6805a8b08cd04aed5e0d74f82ff5/vlmeval/vlm/internvl_chat.py#L324).
**Note: If both `model.build_prompt()` and `dataset.build_prompt()` are defined, `model.build_prompt()` will take precedence over `dataset.build_prompt()`, effectively overriding it.**
Some models, such as Qwen2VL and InternVL, define extensive prompt-building methods for various types of benchmarks. To provide more flexibility in adapting to different benchmarks, VLMEvalKit allows users to customize the `model.use_custom_prompt()` function within the model. By adding or modifying the `use_custom_prompt()` function, you can decide which benchmarks should utilize the model's custom prompt logic. Below is an example:
```python
def use_custom_prompt(self, dataset: str) -> bool:
from vlmeval.dataset import DATASET_TYPE, DATASET_MODALITY
dataset_type = DATASET_TYPE(dataset, default=None)
if not self._use_custom_prompt:
return False
if listinstr(['MMVet'], dataset):
return True
if dataset_type == 'MCQ':
return True
if DATASET_MODALITY(dataset) == 'VIDEO':
return False
return False
```
Only when the `use_custom_prompt()` function returns `True` will VLMEvalKit call the model's `build_prompt()` function for the current benchmark.
With this approach, you can flexibly control which benchmarks use the model's custom prompt logic based on your specific needs, thereby better adapting to different models and tasks.
#### Model Splitting
Currently, VLMEvalKit automatically supports GPU resource allocation and model splitting between processes on the same machine. This feature is supported when the inference backend is `lmdeploy` or `transformers`, with the following behaviors:
- When launching with `python` command, the model is by default allocated to all available GPUs. If you want to specify which GPUs to use, you can use `CUDA_VISIBLE_DEVICES` environment variable.
- When starting with `torchrun` command, each model instance will be allocated to `N_GPU // N_PROC` GPUs, where `N_PROC` is the number of processes specified by the `--nproc-per-node` parameter in the torchrun command. The value of `N_GPU` is determined as follows:
- If `CUDA_VISIBLE_DEVICES` environment variable is not set, `N_GPU` will be the total number of available GPUs.
- If `CUDA_VISIBLE_DEVICES` environment variable is set, `N_GPU` will be the number of GPUs specified by the `CUDA_VISIBLE_DEVICES` environment variable, and only the specified GPUs will be utilized.
Below are specific examples of running evaluation tasks on a machine equipped with 8 GPUs:
```bash
<!-- Launch two model instances in data parallel, each instance using 4 GPUs -->
torchrun --nproc-per-node=2 run.py --data MMBench_DEV_EN --model InternVL3-78B
<!-- Launch one model instance, using all 8 GPUs -->
python run.py --data MMBench_DEV_EN --model InternVL3-78B
<!-- Launch three model instances, each instance using 2 GPUs, GPU 0 and 7 are not used -->
CUDA_VISIBLE_DEVICES=1,2,3,4,5,6 torchrun --nproc-per-node=3 run.py --data MMBench_DEV_EN --model InternVL3-38B
```
PS: The feature is not compatible with `vllm` backend. When you evaluate a model with `vllm` backend, please use `python` to launch, and all visible GPU devices will be used.
#### Performance Discrepancies
Model performance may vary across different environments. As a result, you might observe discrepancies between your evaluation results and those listed on the official VLMEvalKit leaderboard. These differences could be attributed to variations in versions of libraries such as `transformers`, `cuda`, and `torch`.
Besides, if you encounter unexpected performance, we recommend first reviewing the local generation records (`{model}_{dataset}.xlsx`) or the evaluation records (`{model}_{dataset}_{judge_model}.xlsx`). This may help you better understand the evaluation outcomes and identify potential issues.
## Deploy a local language model as the judge / choice extractor
The default setting mentioned above uses OpenAI's GPT as the judge LLM. However, you can also deploy a local judge LLM with [LMDeploy](https://github.com/InternLM/lmdeploy).
First install:
```
pip install lmdeploy openai
```
And then deploy a local judge LLM with the single line of code. LMDeploy will automatically download the model from Huggingface. Assuming we use internlm2-chat-1_8b as the judge, port 23333, and the key sk-123456 (the key must start with "sk-" and follow with any number you like):
```
lmdeploy serve api_server internlm/internlm2-chat-1_8b --server-port 23333
```
You need to get the model name registered by LMDeploy with the following python code:
```
from openai import OpenAI
client = OpenAI(
api_key='sk-123456',
base_url="http://0.0.0.0:23333/v1"
)
model_name = client.models.list().data[0].id
```
Now set some environment variables to tell VLMEvalKit how to use the local judge LLM. As mentioned above, you can also set them in `$VLMEvalKit/.env` file:
```
OPENAI_API_KEY=sk-123456
OPENAI_API_BASE=http://0.0.0.0:23333/v1/chat/completions
LOCAL_LLM=<model_name you get>
```
Finally, you can run the commands in step 2 to evaluate your VLM with the local judge LLM.
Note that
- If you hope to deploy the judge LLM in a single GPU and evaluate your VLM on other GPUs because of limited GPU memory, try `CUDA_VISIBLE_DEVICES=x` like
```
CUDA_VISIBLE_DEVICES=0 lmdeploy serve api_server internlm/internlm2-chat-1_8b --server-port 23333
CUDA_VISIBLE_DEVICES=1,2,3 torchrun --nproc-per-node=3 run.py --data HallusionBench --model qwen_chat --verbose
```
- If the local judge LLM is not good enough in following the instructions, the evaluation may fail. Please report such failures (e.g., by issues).
- It's possible to deploy the judge LLM in different ways, e.g., use a private LLM (not from HuggingFace) or use a quantized LLM. Please refer to the [LMDeploy doc](https://lmdeploy.readthedocs.io/en/latest/serving/api_server.html). You can use any other deployment framework if they support OpenAI API.
### Using LMDeploy to Accelerate Evaluation and Inference
You can refer this [doc](/docs/en/EvalByLMDeploy.md)
@@ -0,0 +1,63 @@
.header-logo {
background-image: url("../image/logo.svg");
background-size: 275px 80px;
height: 80px;
width: 275px;
}
@media screen and (min-width: 1100px) {
.header-logo {
top: -25px;
}
}
pre {
white-space: pre;
}
@media screen and (min-width: 2000px) {
.pytorch-content-left {
width: 1200px;
margin-left: 30px;
}
article.pytorch-article {
max-width: 1200px;
}
.pytorch-breadcrumbs-wrapper {
width: 1200px;
}
.pytorch-right-menu.scrolling-fixed {
position: fixed;
top: 45px;
left: 1580px;
}
}
article.pytorch-article section code {
padding: .2em .4em;
background-color: #f3f4f7;
border-radius: 5px;
}
/* Disable the change in tables */
article.pytorch-article section table code {
padding: unset;
background-color: unset;
border-radius: unset;
}
table.autosummary td {
width: 50%
}
img.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
article.pytorch-article p.rubric {
font-weight: bold;
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" version="1.1" width="210" height="36" viewBox="0 0 1920 480" xml:space="preserve">
<desc>Created with Fabric.js 5.3.0</desc>
<defs>
</defs>
<g transform="matrix(8.6096948697 0 0 8.6096948697 283.4607944077 326.096948697)" id="2rbaYufxVtcDPCyBcyhLL" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(88,120,180); fill-rule: nonzero; opacity: 1;" transform=" translate(-19.1, -28)" d="M 16.5 22.6 L 10.1 25.700000000000003 L 15.399999999999999 25.500000000000004 L 16.5 22.6 z M 12.3 33.6 L 13.4 30.700000000000003 L 8.100000000000001 30.900000000000002 L 12.3 33.6 z M 21.6 33.3 L 28 30.199999999999996 L 22.7 30.399999999999995 L 21.6 33.3 z M 25.8 22.4 L 24.7 25.299999999999997 L 30 25.099999999999998 L 25.8 22.4 z M 31.5 26.2 L 24.4 26.4 L 22.7 25.299999999999997 L 24.2 21.299999999999997 L 22.2 20 L 19 21.5 L 17.5 25.4 L 14.8 26.7 L 7.700000000000001 26.9 L 4.500000000000001 28.4 L 6.600000000000001 29.799999999999997 L 13.700000000000001 29.599999999999998 L 13.700000000000001 29.599999999999998 L 15.4 30.7 L 13.9 34.7 L 16 36 L 19.2 34.5 L 20.7 30.6 L 20.7 30.6 L 23.3 29.400000000000002 L 23.3 29.400000000000002 L 30.5 29.200000000000003 L 33.7 27.700000000000003 L 31.5 26.2 z M 20.2 28.7 C 19.2 29.2 17.9 29.2 17.2 28.8 C 16.599999999999998 28.400000000000002 16.8 27.6 17.8 27.2 C 18.8 26.7 20.1 26.7 20.8 27.099999999999998 C 21.5 27.5 21.2 28.2 20.2 28.7 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 351.9078686218 195.2295866776)" id="Gj0NH9qgtM_hm6hdZ_Tf1" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(54,86,155); fill-rule: nonzero; opacity: 1;" transform=" translate(-27.05, -12.8)" d="M 33.5 19.8 L 32.2 13.3 L 30.700000000000003 15.200000000000001 L 33.5 19.8 z M 27.5 5.1 L 23.3 2.3999999999999995 L 26 7 L 27.5 5.1 z M 20.7 5.7 L 22 12.2 L 23.5 10.299999999999999 L 20.7 5.7 z M 26.8 20.4 L 31 23.099999999999998 L 28.3 18.5 L 26.8 20.4 z M 34 22.3 L 30.4 16.1 L 30.4 16.1 L 29.9 13.400000000000002 L 31.9 10.800000000000002 L 31.299999999999997 7.600000000000002 L 29.199999999999996 6.200000000000003 L 27.199999999999996 8.800000000000002 L 25.499999999999996 7.700000000000003 L 21.799999999999997 1.400000000000003 L 19.6 0 L 20.200000000000003 3.2 L 23.900000000000002 9.5 L 23.900000000000002 9.5 L 24.400000000000002 12.1 L 24.400000000000002 12.1 L 22.400000000000002 14.7 L 23.000000000000004 17.9 L 25.100000000000005 19.299999999999997 L 27.000000000000004 16.799999999999997 L 28.700000000000003 17.9 L 32.400000000000006 24.2 L 34.50000000000001 25.599999999999998 L 34 22.3 z M 27.5 14.6 C 26.9 14.2 26.2 13 26 12 C 25.8 11 26.2 10.5 26.8 10.9 C 27.400000000000002 11.3 28.1 12.5 28.3 13.5 C 28.5 14.6 28.1 15.1 27.5 14.6 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 209.8479032717 200.3954035994)" id="lmxdEhRpowSXVKC1LScVi" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1;" transform=" translate(-10.55, -13.4)" d="M 12 2.8 L 5.6 5.9 L 9.399999999999999 7.6000000000000005 L 12 2.8 z M 1.1 14.4 L 2.4000000000000004 20.9 L 5 16.099999999999998 L 1.1 14.4 z M 9.1 24 L 15.5 20.9 L 11.7 19.2 L 9.1 24 z M 20 12.4 L 18.7 5.9 L 16.099999999999998 10.7 L 20 12.4 z M 20.4 14.9 L 15.299999999999999 12.600000000000001 L 15.299999999999999 12.600000000000001 L 14.799999999999999 9.900000000000002 L 18.299999999999997 3.400000000000002 L 17.699999999999996 0.20000000000000195 L 14.499999999999996 1.700000000000002 L 11 8.1 L 8.3 9.4 L 8.3 9.4 L 3.2 7.1 L 0 8.6 L 0.6 11.8 L 5.8 14.100000000000001 L 6.3 16.8 L 6.3 16.8 L 2.8 23.4 L 3.4 26.599999999999998 L 6.6 25.099999999999998 L 10.1 18.599999999999998 L 12.7 17.4 L 12.7 17.4 L 17.9 19.799999999999997 L 21.099999999999998 18.299999999999997 L 20.4 14.9 z M 10.9 15.2 C 9.9 15.7 9 15.2 8.8 14.2 C 8.600000000000001 13.2 9.200000000000001 12 10.200000000000001 11.5 C 11.200000000000001 11 12.100000000000001 11.5 12.3 12.5 C 12.5 13.5 11.9 14.7 10.9 15.2 z" stroke-linecap="round" />
</g>
<g transform="matrix(1 0 0 1 1109.6072390741 240)" style="" id="IiDed4ej1oioRNDwSqAwf">
<text xml:space="preserve" font-family="Amethysta" font-size="225" font-style="normal" font-weight="normal" line-height="1" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1; white-space: pre;"><tspan x="-714.0188713264" y="72.3065" style="white-space: pre; "> VLMEvalKit</tspan></text>
<style>
@font-face {
font-family: "Amethysta";
font-weight: normal;
src: url("data:font/ttf;base64,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 truncated
}
</style></g></svg>

After

Width:  |  Height:  |  Size: 87 KiB

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 34.59 36">
<defs>
<style>
.cls-1 {
fill: #36569b;
}
.cls-2 {
fill: #1b3882;
}
.cls-3 {
fill: #5878b4;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<g>
<g id="_3" data-name="3">
<path class="cls-3" d="m16.53,22.65l-6.37,3.07,5.27-.16,1.1-2.91Zm-4.19,10.95l1.12-2.91-5.27.17,4.15,2.74Zm9.3-.29l6.37-3.07-5.27.16-1.1,2.91Zm4.19-10.95l-1.12,2.91,5.27-.17-4.15-2.74Zm5.72,3.81l-7.08.23-1.73-1.14,1.5-3.95-2.06-1.36-3.16,1.53-1.48,3.89-2.67,1.29-7.14.23-3.16,1.53,2.07,1.36,7.13-.23h0s1.69,1.11,1.69,1.11l-1.51,3.98,2.06,1.36,3.16-1.53,1.5-3.95h0s2.56-1.24,2.56-1.24h0s7.23-.24,7.23-.24l3.16-1.53-2.06-1.36Zm-11.29,2.56c-.99.48-2.31.52-2.96.1-.65-.42-.37-1.15.62-1.63.99-.48,2.31-.52,2.96-.1.65.42.37,1.15-.62,1.63Z"/>
</g>
<g id="_2" data-name="2">
<path class="cls-1" d="m33.5,19.84l-1.26-6.51-1.46,1.88,2.72,4.63Zm-6.05-14.69l-4.16-2.74,2.71,4.64,1.45-1.89Zm-6.73.58l1.26,6.51,1.46-1.88-2.72-4.63Zm6.05,14.69l4.16,2.74-2.71-4.64-1.45,1.89Zm7.19,1.91l-3.63-6.2h0s-.53-2.74-.53-2.74l1.96-2.56-.63-3.23-2.07-1.36-1.96,2.56-1.69-1.11-3.71-6.33-2.07-1.36.63,3.23,3.68,6.28h0s.51,2.62.51,2.62h0s-1.99,2.6-1.99,2.6l.63,3.23,2.06,1.36,1.95-2.54,1.73,1.14,3.69,6.29,2.07,1.36-.63-3.23Zm-6.47-7.7c-.65-.42-1.33-1.59-1.52-2.6-.2-1.01.17-1.49.81-1.06.65.42,1.33,1.59,1.52,2.6.2,1.01-.17,1.49-.81,1.06Z"/>
</g>
<g id="_1" data-name="1">
<path class="cls-2" d="m11.96,2.82l-6.37,3.07,3.81,1.74,2.55-4.81ZM1.07,14.37l1.26,6.53,2.56-4.8-3.82-1.73Zm7.99,9.59l6.37-3.07-3.81-1.74-2.55,4.81Zm10.89-11.55l-1.26-6.53-2.56,4.8,3.82,1.73Zm.45,2.53l-5.13-2.32h0s-.53-2.71-.53-2.71l3.47-6.53-.63-3.24-3.16,1.53-3.42,6.43-2.67,1.29h0s-5.17-2.34-5.17-2.34l-3.16,1.53.63,3.24,5.17,2.33.51,2.65h0s-3.49,6.57-3.49,6.57l.63,3.24,3.16-1.53,3.46-6.52,2.56-1.24h0s5.24,2.37,5.24,2.37l3.16-1.53-.63-3.24Zm-9.52.24c-.99.48-1.95.04-2.14-.97-.2-1.01.44-2.22,1.43-2.69.99-.48,1.95-.04,2.14.97.2,1.01-.44,2.22-1.43,2.7Z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -0,0 +1,10 @@
var collapsedSections = [];
$(document).ready(function () {
$('.model-summary').DataTable({
"stateSave": false,
"lengthChange": false,
"pageLength": 20,
"order": []
});
});
@@ -0,0 +1,18 @@
{% extends "layout.html" %}
{% block body %}
<h1>Page Not Found</h1>
<p>
The page you are looking for cannot be found.
</p>
<p>
If you just switched documentation versions, it is likely that the page you were on is moved. You can look for it in
the content table left, or go to <a href="{{ pathto(root_doc) }}">the homepage</a>.
</p>
<!-- <p>
If you cannot find documentation you want, please <a
href="">open an issue</a> to tell us!
</p> -->
{% endblock %}
@@ -0,0 +1,13 @@
.. role:: hidden
:class: hidden-section
.. currentmodule:: {{ module }}
{{ name | underline}}
.. autoclass:: {{ name }}
:members:
..
autogenerated from _templates/autosummary/class.rst
note it does not have :inherited-members:
@@ -0,0 +1,14 @@
.. role:: hidden
:class: hidden-section
.. currentmodule:: {{ module }}
{{ name | underline}}
.. autoclass:: {{ name }}
:members:
:special-members: __call__
..
autogenerated from _templates/callable.rst
note it does not have :inherited-members:
+234
View File
@@ -0,0 +1,234 @@
# flake8: noqa
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import ast
import subprocess
import sys
import pytorch_sphinx_theme
from sphinx.builders.html import StandaloneHTMLBuilder
sys.path.insert(0, os.path.abspath('../../'))
# -- Project information -----------------------------------------------------
project = 'VLMEvalKit'
copyright = '2023, VLMEvalKit'
author = 'VLMEvalKit Authors'
# The full version, including alpha/beta/rc tags
version_file = '../../vlmeval/__init__.py'
def get_version():
with open(version_file, 'r') as f:
file_content = f.read()
# Parse the file content into an abstract syntax tree (AST)
tree = ast.parse(file_content, filename=version_file)
# Iterate through the body of the AST, looking for an assignment to __version__
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == '__version__':
return node.value.s
raise ValueError('__version__ not found')
release = get_version()
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'myst_parser',
'sphinx_copybutton',
'sphinx_tabs.tabs',
'notfound.extension',
'sphinxcontrib.jquery',
'sphinx_design',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = {
'.rst': 'restructuredtext',
'.md': 'markdown',
}
language = 'en'
# The master toctree document.
root_doc = 'index'
html_context = {
'github_version': 'latest',
}
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'pytorch_sphinx_theme'
html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# yapf: disable
html_theme_options = {
'menu': [
{
'name': 'GitHub',
'url': 'https://github.com/open-compass/VLMEvalKit'
},
],
# Specify the language of shared menu
'menu_lang': 'en',
# Disable the default edit on GitHub
'default_edit_on_github': False,
}
# yapf: enable
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = [
'https://cdn.datatables.net/v/bs4/dt-1.12.1/datatables.min.css',
'css/readthedocs.css'
]
html_js_files = [
'https://cdn.datatables.net/v/bs4/dt-1.12.1/datatables.min.js',
'js/custom.js'
]
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'vlmevalkitdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(root_doc, 'vlmevalkit.tex', 'VLMEvalKit Documentation', author,
'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(root_doc, 'vlmevalkit', 'VLMEvalKit Documentation', [author],
1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(root_doc, 'vlmevalkit', 'VLMEvalKit Documentation', author,
'VLMEvalKit Authors', 'AGI evaluation toolbox and benchmark.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# set priority when building html
StandaloneHTMLBuilder.supported_image_types = [
'image/svg+xml', 'image/gif', 'image/png', 'image/jpeg'
]
# -- Extension configuration -------------------------------------------------
# Ignore >>> when copying code
copybutton_prompt_text = r'>>> |\.\.\. '
copybutton_prompt_is_regexp = True
# Auto-generated header anchors
myst_heading_anchors = 3
# Enable "colon_fence" extension of myst.
myst_enable_extensions = ['colon_fence', 'dollarmath']
# Configuration for intersphinx
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'numpy': ('https://numpy.org/doc/stable', None),
'torch': ('https://pytorch.org/docs/stable/', None),
'mmengine': ('https://mmengine.readthedocs.io/en/latest/', None),
'transformers':
('https://huggingface.co/docs/transformers/main/en/', None),
}
napoleon_custom_sections = [
# Custom sections for data elements.
('Meta fields', 'params_style'),
('Data fields', 'params_style'),
]
# Disable docstring inheritance
autodoc_inherit_docstrings = False
# Mock some imports during generate API docs.
autodoc_mock_imports = ['rich', 'attr', 'einops']
# Disable displaying type annotations, these can be very verbose
autodoc_typehints = 'none'
# The not found page
notfound_template = '404.html'
+2
View File
@@ -0,0 +1,2 @@
[html writers]
table_style: colwidths-auto
+41
View File
@@ -0,0 +1,41 @@
Welcome to the VLMEvalKit Tutorial!
==========================================
VLMEvalKit Getting Started Guide
-------------------------------
To help users get started quickly, we recommend the following process:
- For users who want to use VLMEvalKit, we recommend reading the "Start Your First Step" section to set up the environment and start a mini-experiment to familiarize yourself with the process.
- If you want to customize more modules, such as adding datasets and models, we provide an "Advanced Tutorial."
We always welcome users' PRs (Pull Requests) and Issues to improve VLMEvalKit!
.. _Start Your First Step:
.. toctree::
:maxdepth: 1
:caption: Start Your First Step
Quickstart.md
.. _Advanced Tutorial:
.. toctree::
:maxdepth: 1
:caption: Advanced Tutorial
Development.md
ConfigSystem.md
.. _Other Notes:
.. toctree::
:maxdepth: 1
:caption: Other Notes
Contributors.md
Index and Tables
==================
* :ref:`genindex`
* :ref:`search`
+117
View File
@@ -0,0 +1,117 @@
<div align="center">
![LOGO](http://opencompass.openxlab.space/utils/MMLB.jpg)
<b>VLMEvalKit: 大規模視覚言語モデルの評価ツールキット</b>
[![][github-contributors-shield]][github-contributors-link] • [![][github-forks-shield]][github-forks-link] • [![][github-stars-shield]][github-stars-link] • [![][github-issues-shield]][github-issues-link] • [![][github-license-shield]][github-license-link]
[English](/README.md) | [简体中文](/docs/zh-CN/README_zh-CN.md) | 日本語
<a href="https://rank.opencompass.org.cn/leaderboard-multimodal">🏆 OpenCompass Learderboard </a> •
<a href="#-datasets-models-and-evaluation-results">📊Datasets & Models </a> •
<a href="#%EF%B8%8F-quickstart">🏗️Quickstart </a> •
<a href="#%EF%B8%8F-development-guide">🛠️Development </a> •
<a href="#-the-goal-of-vlmevalkit">🎯Goal </a> •
<a href="#%EF%B8%8F-citation">🖊️Citation </a>
<a href="https://huggingface.co/spaces/opencompass/open_vlm_leaderboard">🤗 HF Leaderboard</a> •
<a href="https://huggingface.co/datasets/VLMEval/OpenVLMRecords">🤗 Evaluation Records</a> •
<a href="https://discord.gg/evDT4GZmxN">🔊 Discord Channel</a> •
<a href="https://www.arxiv.org/abs/2407.11691">📝 Technical Report</a>
</div>
**VLMEvalKit**(pythonパッケージ名は**vlmeval**)は、**大規模視覚言語モデル(LVLMs)**の**オープンソース評価ツールキット**です。このツールキットは、複数のリポジトリでのデータ準備という重労働なしに、さまざまなベンチマークでLVLMsの**ワンコマンド評価**を可能にします。VLMEvalKitでは、すべてのLVLMsに対して**生成ベースの評価**を採用し、**正確なマッチング**と**LLMベースの回答抽出**の両方で得られた評価結果を提供します。
PS: 日本語の README には最新のアップデートがすべて含まれていない場合があります。英語版をご確認ください。
## 📊 データセット、モデル、および評価結果
**公式のマルチモーダルリーダーボードでのパフォーマンス数値は、ここからダウンロードできます!**
[**OpenVLM Leaderboard**](https://huggingface.co/spaces/opencompass/open_vlm_leaderboard): [すべての詳細な結果をダウンロード](http://opencompass.openxlab.space/assets/OpenVLM.json)。
**Supported Benchmarks** in [**VLMEvalKit Features**](https://aicarrier.feishu.cn/wiki/Qp7wwSzQ9iK1Y6kNUJVcr6zTnPe?table=tblsdEpLieDoCxtb) を確認して、すべてのサポートされているベンチマーク(70以上)を表示してください。
**Supported LMMs** in [**VLMEvalKit Features**](https://aicarrier.feishu.cn/wiki/Qp7wwSzQ9iK1Y6kNUJVcr6zTnPe?table=tblsdEpLieDoCxtb) を確認して、すべてのサポートされている LMMs(200以上)を表示してください。
**Transformersバージョンの推奨事項:**
特定のtransformerバージョンで一部のVLMが実行できない可能性があることに注意してください。各VLMを評価するために、以下の設定を推奨します:
- **`transformers==4.33.0`を使用してください**: `Qwenシリーズ`, `Monkeyシリーズ`, `InternLM-XComposerシリーズ`, `mPLUG-Owl2`, `OpenFlamingo v2`, `IDEFICSシリーズ`, `VisualGLM`, `MMAlaya`, `ShareCaptioner`, `MiniGPT-4シリーズ`, `InstructBLIPシリーズ`, `PandaGPT`, `VXVERSE`, `GLM-4v-9B`.
- **`transformers==4.37.0`を使用してください**: `LLaVAシリーズ`, `ShareGPT4Vシリーズ`, `TransCore-M`, `LLaVA (XTuner)`, `CogVLMシリーズ`, `EMU2シリーズ`, `Yi-VLシリーズ`, `MiniCPM-[V1/V2]`, `OmniLMM-12B`, `DeepSeek-VLシリーズ`, `InternVLシリーズ`, `Cambrianシリーズ`, `VILA-VLシリーズ`.
- **`transformers==4.40.0`を使用してください**: `IDEFICS2`, `Bunny-Llama3`, `MiniCPM-Llama3-V2.5`, `360VL-70B`, `Phi-3-Vision`, `WeMM`.
- **`transformers==4.42.0`を使用してください**: `AKI`.
- **`transformers==latest`を使用してください**: `LLaVA-Nextシリーズ`, `PaliGemma-3B`, `Chameleon-VLシリーズ`, `Video-LLaVA-7B-HF`, `Ovis1.5シリーズ`, `Mantisシリーズ`, `MiniCPM-V2.6`.
```python
# デモ
from vlmeval.config import supported_VLM
model = supported_VLM['idefics_9b_instruct']()
# 単一画像のフォワード
ret = model.generate(['assets/apple.jpg', 'この画像には何がありますか?'])
print(ret) # この画像には葉がついた赤いリンゴがあります。
# 複数画像のフォワード
ret = model.generate(['assets/apple.jpg', 'assets/apple.jpg', '提供された画像にはリンゴが何個ありますか?'])
print(ret) # 提供された画像にはリンゴが2個あります。
```
## 🏗️ クイックスタート
クイックスタートガイドについては、[クイックスタート](/docs/en/Quickstart.md)を参照してください。
## 🛠️ 開発ガイド
カスタムベンチマーク、VLMsを開発するか、単に**VLMEvalKit**に他のコードを貢献する場合は、[開発ガイド](/docs/en/Development.md)を参照してください。
コミュニティからの共有を奨励し、それに応じたクレジットを共有するために、次回のレポート更新では以下のことを実施します:
- 全ての貢献に対して感謝の意を示します
- 新しいモデル、評価セット、または主要な機能への3つ以上の主要な貢献を持つ貢献者は、テクニカルレポートの著者リストに加わることができます。適格な貢献者は、issueを作成するか、または[VLM評価キット ディスコードチャンネル](https://discord.com/invite/evDT4GZmxN)で kennyutc にDMを送ることができます。私たちはそれに応じてフォローアップします。
## 🎯 VLMEvalKitの目標
**このコードベースは以下を目的として設計されています:**
1. 研究者や開発者が既存のLVLMsを評価し、評価結果を**簡単に再現できるようにする**ための**使いやすい**、**オープンソースの評価ツールキット**を提供します。
2. VLMの開発者が自分のモデルを簡単に評価できるようにします。複数のサポートされているベンチマークでVLMを評価するには、単一の`generate_inner()`関数を**実装するだけで**、他のすべてのワークロード(データのダウンロード、データの前処理、予測の推論、メトリックの計算)はコードベースによって処理されます。
**このコードベースは以下を目的として設計されていません:**
1. すべての**第三者ベンチマーク**の元の論文で報告された正確な精度数値を再現すること。その理由は2つあります:
1. VLMEvalKitは、すべてのVLMに対して**生成ベースの評価**を使用します(オプションで**LLMベースの回答抽出**を使用)。一方、一部のベンチマークは異なるアプローチを使用する場合があります(SEEDBenchはPPLベースの評価を使用します)。これらのベンチマークについては、対応する結果で両方のスコアを比較します。開発者には、コードベースで他の評価パラダイムをサポートすることをお勧めします。
2. デフォルトでは、すべてのVLMに対して同じプロンプトテンプレートを使用してベンチマークを評価します。一方、**一部のVLMには特定のプロンプトテンプレートがある**場合があります(現時点ではコードベースでカバーされていない場合があります)。VLMの開発者には、現在カバーされていない場合でも、VLMEvalKitで独自のプロンプトテンプレートを実装することをお勧めします。これにより、再現性が向上します。
## 🖊️ 引用
この作業が役立つ場合は、このリポジトリに**スター🌟**を付けてください。サポートありがとうございます!
[![Stargazers repo roster for @open-compass/VLMEvalKit](https://reporoster.com/stars/open-compass/VLMEvalKit)](https://github.com/open-compass/VLMEvalKit/stargazers)
研究でVLMEvalKitを使用する場合、または公開されたオープンソースの評価結果を参照する場合は、以下のBibTeXエントリと、使用した特定のVLM/ベンチマークに対応するBibTexエントリを使用してください。
```bib
@misc{duan2024vlmevalkit,
title={VLMEvalKit: An Open-Source Toolkit for Evaluating Large Multi-Modality Models},
author={Haodong Duan and Junming Yang and Yuxuan Qiao and Xinyu Fang and Lin Chen and Yuan Liu and Xiaoyi Dong and Yuhang Zang and Pan Zhang and Jiaqi Wang and Dahua Lin and Kai Chen},
year={2024},
eprint={2407.11691},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2407.11691},
}
```
<p align="right"><a href="#top">🔝Top に戻る</a></p>
[github-contributors-link]: https://github.com/open-compass/VLMEvalKit/graphs/contributors
[github-contributors-shield]: https://img.shields.io/github/contributors/open-compass/VLMEvalKit?color=c4f042&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/open-compass/VLMEvalKit/network/members
[github-forks-shield]: https://img.shields.io/github/forks/open-compass/VLMEvalKit?color=8ae8ff&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/open-compass/VLMEvalKit/issues
[github-issues-shield]: https://img.shields.io/github/issues/open-compass/VLMEvalKit?color=ff80eb&labelColor=black&style=flat-square
[github-license-link]: https://github.com/open-compass/VLMEvalKit/blob/main/LICENSE
[github-license-shield]: https://img.shields.io/github/license/open-compass/VLMEvalKit?color=white&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/open-compass/VLMEvalKit/stargazers
[github-stars-shield]: https://img.shields.io/github/stars/open-compass/VLMEvalKit?color=ffcb47&labelColor=black&style=flat-square
@@ -0,0 +1,17 @@
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.8"
formats:
- epub
sphinx:
configuration: docs/zh-CN/conf.py
python:
install:
- requirements: requirements/docs.txt
@@ -0,0 +1,69 @@
# 配置系统
默认情况下,VLMEvalKit通过在`run.py`脚本中使用`--model`和`--data`参数设置模型名称(在`/vlmeval/config.py`中定义)和数据集名称(在`vlmeval/dataset/__init__.py` 或 `vlmeval/dataset/video_dataset_config.py` 中定义)来启动评估。这种方法在大多数情况下简单且高效,但当用户希望使用不同设置评估多个模型/数据集时,可能不够灵活。
为了解决这个问题,VLMEvalKit提供了一个更灵活的配置系统。用户可以在json文件中指定模型和数据集设置,并通过`--config`参数将配置文件的路径传递给`run.py`脚本。以下是一个示例配置json:
```json
{
"model": {
"GPT4o_20240806_T00_HIGH": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 0,
"img_detail": "high"
},
"GPT4o_20240806_T10_Low": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 1.0,
"img_detail": "low"
},
"GPT4o_20241120": {}
},
"data": {
"MME-RealWorld-Lite": {
"class": "MMERealWorld",
"dataset": "MME-RealWorld-Lite"
},
"MMBench_DEV_EN_V11": {
"class": "ImageMCQDataset",
"dataset": "MMBench_DEV_EN_V11"
},
"MMBench_Video_8frame_nopack":{},
"Video-MME_16frame_subs": {
"class": "VideoMME",
"dataset": "Video-MME",
"nframe": 16,
"use_subtitle": true
}
}
}
```
配置json的解释:
1. 现在我们支持两个字段:`model`和`data`,每个字段都是一个字典。字典的键是模型/数据集的名称(由用户设置),值是模型/数据集的设置。
2. 对于`model`中的项目,值是一个包含以下键的字典:
- `class`:模型的类名,应该是`vlmeval/vlm/__init__.py`(开源模型)或`vlmeval/api/__init__.py`(API模型)中定义的类名。
- 其他kwargs:其他kwargs是模型特定的参数,请参考模型类的定义以获取详细用法。例如,`model`、`temperature`、`img_detail`是`GPT4V`类的参数。值得注意的是,大多数模型类都需要`model`参数。
- Tip:在位于`vlmeval/config.py`的变量`supported_VLM`中的已经被定义的模型可以作为`model`的键,而不需要填对应的值即可启动。例如,`GPT4o_20240806_T00_HIGH: {}`是等价于`GPT4o_20240806_T00_HIGH: {'class': 'GPT4V', 'model': 'gpt-4o-2024-08-06', 'temperature': 0, 'img_size': -1, 'img_detail': 'high', 'retry': 10, 'verbose': False}`。
3. 对于字典`data`,我们建议用户使用官方数据集名称作为键(或键的一部分),因为我们经常根据数据集名称确定后处理/判断设置。对于`data`中的项目,值是一个包含以下键的字典:
- `class`:数据集的类名,应该是`vlmeval/dataset/__init__.py`中定义的类名。
- 其他kwargs:其他kwargs是数据集特定的参数,请参考数据集类的定义以获取详细用法。通常,大多数数据集类都需要`dataset`参数。大多数视频数据集类都需要 `nframe` 或 `fps` 参数。
- Tip:在位于`vlmeval/dataset/video_dataset_config.py`的变量`supported_video_dataset`中的已经被定义的数据集可以作为`data`的键,而不需要填对应的值即可启动。例如,`MMBench_Video_8frame_nopack: {}`是等价于`MMBench_Video_8frame_nopack: {'class': 'MMBenchVideo', 'dataset': 'MMBench-Video', 'nframe': 8, 'pack': False}`。
将示例配置json保存为`config.json`,您可以通过以下命令启动评估:
```bash
python run.py --config config.json
```
这将在工作目录`$WORK_DIR`下生成以下输出文件(格式为`{$WORK_DIR}/{$MODEL_NAME}/{$MODEL_NAME}_{$DATASET_NAME}_*`):
- `$WORK_DIR/GPT4o_20240806_T00_HIGH/GPT4o_20240806_T00_HIGH_MME-RealWorld-Lite*`
- `$WORK_DIR/GPT4o_20240806_T10_Low/GPT4o_20240806_T10_Low_MME-RealWorld-Lite*`
- `$WORK_DIR/GPT4o_20240806_T00_HIGH/GPT4o_20240806_T00_HIGH_MMBench_DEV_EN_V11*`
- `$WORK_DIR/GPT4o_20240806_T10_Low/GPT4o_20240806_T10_Low_MMBench_DEV_EN_V11*`
......
+139
View File
@@ -0,0 +1,139 @@
# 🛠️ 如何在 VLMEvalKit 中实现一个新的 Benchmark 或多模态模型(VLM)
## 实现一个新的 benchmark
示例 PR: **添加 Math-Vision Benchmark** ([#292](https://github.com/open-compass/VLMEvalKit/pull/292/files))
目前在 VLMEvalKit 中,benchmark 以数据集类的形式呈现,当你新增一个 benchmark 时,你可以选择复用现有的数据集类 (如单选题 benchmark 可复用 `ImageMCQDataset`),或是实现新的数据集类。你的数据集类必须支持以下两种方法 (复用父类或自行实现):
- `build_prompt(self, line)`: 方法输入 `line` 类型为 int (对应数据 index) 或 `pd.Series` (对应数据原始 record)。方法输出一条 `multi-modal message` 作为多模态模型输入,`multi-modal message` 是一个图文交错的列表,如以下格式 (一图一文): `[dict(type='image', value=IMAGE_PTH), dict(type='text', value=prompt)]`。
- `evaluate(self, eval_file, **judge_kwargs)`: 方法输入 `eval_file` 为多模态模型的预测结果 (多以 `.xlsx` 格式存在),如 benchmark evaluation 需要大语言模型 (一般为 GPT) 辅助,则 `judge_kwargs` 传入大语言模型的参数。方法输出 benchmark 的评测结果,以 `dict` 或 `pd.DataFrame` 的形式。
以下,我们简述新增数据集的通常步骤:
### 1. TSV 数据文件准备 (图文评测集)
目前,我们将每一个 benchmark 数据集设置为一个单独的 TSV 文件。在推理过程中,数据文件将从数据集定义的 `DATASET_URL` 链接地址自动下载到 `$LMUData` 中(如果没有明确设置的话,默认路径是 `$HOME/LMUData`)。你可以将准备好的 TSV 文件上传到一个可下载的地址(如:huggingface),或发送给我们 <opencompass@pjlab.org.cn>,我们将帮助上传数据集到服务器中。此外,你也可以在环境变量中自定义设置下载路径 `LMUData=/path/to/your/data`。
TSV 文件中的内容组成为:
| 数据集名称 \ 字段 | index | image | image_path | question | hint | multi-choice<br>options | answer | category | l2-category | split |
| ---------------------- | ----- | ----- | ---------- | -------- | ---- | ----------------------- | ------ | -------- | ----------- | ----- |
| MMBench_DEV_[CN/EN] | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| MMBench_TEST_[CN/EN] | ✅ | ✅ | | ✅ | ✅ | ✅ | | ✅ | ✅ | ✅ |
| CCBench | ✅ | ✅ | | ✅ | | ✅ | ✅ | ✅ | | |
| SEEDBench_IMG | ✅ | ✅ | | ✅ | | ✅ | ✅ | ✅ | | |
| MME | ✅ | ✅ | | ✅ | | | ✅ | ✅ | | |
| MMVet | ✅ | ✅ | | ✅ | | | ✅ | ✅ | | |
| MMMU_DEV_VAL | ✅ | ✅ | ✅ | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |
| COCO_VAL | ✅ | ✅ | | | | | ✅ | | | |
| OCRVQA_[TEST/TESTCORE] | ✅ | ✅ | | ✅ | | | ✅ | | | |
| TextVQA_VAL | ✅ | ✅ | | ✅ | | | ✅ | | | |
| VCR_[EN/ZH]\_[EASY/HARD]_[ALL/500/100] | ✅ | ✅ | | ✅ | | | ✅ | | | |
<div align="center"><b>表 1. 支持的数据集的 TSV 字段。</b></div>
**TSV 中必须字段的介绍:**
- **index:** 一个整数,`tsv` 中每一行的唯一标识
- **image:** 图片的 base64 编码,你可以使用 `vlmeval/smp/vlm.py` 中实现的API进行编码和解码:
- 编码:`encode_image_to_base64`(对于PIL Image)/ `encode_image_file_to_base64`(对于图片文件路径)
- 解码:`decode_base64_to_image`(对于PIL Image)/ `decode_base64_to_image_file`(对于图片文件路径)
- **question:** 针对图像所提取出的问题,类型为字符串
- **answer:** 问题的答案,类型为字符串,Test 集可缺失这一字段
### 2. 自定义数据集的 prompt 构建
`ImageBaseDataset` 定义了默认的 prompt 格式。如果需要针对数据集添加 prompt,或给模型输入 `Interleave` 的数据格式,可以通过 `build_prompt(line)` 函数实现。该函数输入为,每次给定 TSV 文件中的一行,包含 index, image, question 等内容作为 line。该函数将返回一个多模态消息 `msg` 的字典列表 `[dict(type='image', value=IMAGE_PTH), dict(type='text', value=prompt)]`,包括图片路径和将被输入到 VLMs 的文本 prompt。对于 interleave 类型输入,可以直接将图片路径的字典放置到 image token 位置。
### 3. 自定义数据集的指标实现
增加对 benchmark 的评测需要自定义一个该数据集的 class 对象,从而实现数据集的指标计算。图文多模态数据集均继承自 `vlmeval/dataset/image_base.py` 中的 `ImageBaseDataset` 对象。其中 `TYPE` 定义了数据集的类型;`DATASET_URL` 为数据集的下载地址;`DATASET_MD5` 为数据集文件的 md5 一致性编码检查。
在 class 中**需要实现** `evaluate(eval_file, **judge_kwargs)` 类函数,对自定义的数据集结果进行指标计算和结果输出。函数输入 `eval_file` 为模型预测结果 `{model_name}_{dataset}.xlsx` 的路径。可以通过 `load(eval_file)` 文件将其读取为 panda.DataFrames 类型,其中包含 index, question, answer, category, prediction 等字段。`judge_kwargs` 参数将传递一个评测相关的字典,如:judge 模型的名称,api 请求线程数等。**函数的返回值**为评估完成的准确度等指标,其格式为由 list 组成的字典,并组织成 panda.DataFrames 类型。
## 实现一个新的模型
示例 PR: **支持 LLaVA-Next-Interleave** ([#294](https://github.com/open-compass/VLMEvalKit/pull/294))
**1. 支持 `generate_inner` API (必须)**
现有所有的模型都在 `vlmeval/vlm` 中实现。对于一个最基本的模型,你的模型类**应该实现方法** `generate_inner(msgs, dataset=None)`。这个函数将向 VLM 输入一个多模态数据,并返回 VLM 的预测(一个字符串)。可选参数 `dataset` 可以用作模型在不同推理策略之间切换的标志。
其中多模态消息 `msgs` 是一个字典列表,每个字典有两个键:类型和值:
- `type`:我们目前支持两种类型,选项是 ["image", "text"]。
- `value`:当类型为 `text` 时,值是文本消息(一个字符串);当类型为 `image` 时,值可以是图像文件的本地路径,或者是图像的URL。
> 目前,一个多模态消息可能包含任意交错的图像和文本。如果你的模型不支持这一点,我们推荐的做法是取第一张图像和连接的文本消息作为模型的输入。你可以在模型的 class 中设置 `INTERLEAVE = False` 并调用 `self.message_to_promptimg(message, dataset=dataset)` 函数来获取你的 prompt 和第一张图片的地址。
一些多模态消息的例子:
```python
IMAGE_PTH = 'assets/apple.jpg'
IMAGE_URL = 'https://raw.githubusercontent.com/open-compass/VLMEvalKit/main/assets/apple.jpg'
msg1 = [
dict(type='image', value=IMAGE_PTH),
dict(type='text', value='What is in this image?')
]
msg2 = [
dict(type='image', value=IMAGE_URL),
dict(type='image', value=IMAGE_URL),
dict(type='text', value='How many apples are there in these images?')
]
response = model.generate(msg1)
```
为了方便起见,我们还支持接受字符串列表作为输入。在这种情况下,我们将检查一个字符串是图像路径还是图像 URL,并自动将其转换为 `list[dict]` 格式:
```python
IMAGE_PTH = 'assets/apple.jpg'
IMAGE_URL = 'https://raw.githubusercontent.com/open-compass/VLMEvalKit/main/assets/apple.jpg'
msg1 = [IMAGE_PTH, 'What is in this image?']
msg2 = [IMAGE_URL, IMAGE_URL, 'How many apples are there in these images?']
response = model.generate(msg1)
```
**2. 支持自定义提示词构建 (可选)**
此外,你的模型可以通过实现两个可选方法来支持自定义提示构建:`use_custom_prompt(dataset)` 和 `build_prompt(line, dataset=None)`。
- `use_custom_prompt(dataset)` 将返回一个布尔值,指示模型是否应使用自定义提示构建策略。
- 如果`use_custom_prompt(dataset)`返回 True,`build_prompt(line, dataset)` 应该为相应的数据集返回一个自定义构建的多模态消息,line 数据是一个包含数据样本所需信息的字典。如果`use_custom_prompt(dataset)` 返回False,则将使用默认的 prompt 构建策略。
**3. 支持多轮对话 (可选)**
你可以通过支持 `chat_inner(message, dataset)` API 为你的模型新增多轮对话功能并兼容多轮对话评测。这个 API 输出一个字符串型回复,`message` 包含一个聊天记录的列表,格式如下:
```python
# Assume msg1, msg2, msg3, ... are multi-modal messages following the previously described format
# `chat_inner` take the following chat history list as input:
message = [
dict(role='user', content=msg1),
dict(role='assistant', content=msg2),
dict(role='user', content=msg3),
dict(role='assistant', content=msg4),
......
dict(role='user', content=msgn),
]
# `message` should contain an odd number of chat utterances, the role of utterances should be interleaved "user" and "assistant", with the role of the last utterance to be "user".
# The chat function will call `chat_inner`
response = model.chat(message)
```
### 示例 PRs:
- 不支持交错的图像和文本,且不使用自定义提示的VLM:[[模型] 支持 glm-4v-9b](https://github.com/open-compass/VLMEvalKit/pull/221)
- 支持交错的图像和文本及自定义提示的VLM:[添加 MiniCPM-Llama3-V-2.5](https://github.com/open-compass/VLMEvalKit/pull/205)
- VLM API:[特征添加 glmv](https://github.com/open-compass/VLMEvalKit/pull/201)
## 为 VLMEvalKit 贡献代码
如果你想为 **VLMEvalKit** 贡献代码,请在提交PR之前进行预提交检查。这有助于保持代码整洁。
```bash
# 在VLMEvalKit的目录下,安装预提交 hook:
pip install pre-commit
pre-commit install
pre-commit run --all-files
# 然后提交你的代码。
```
@@ -0,0 +1,28 @@
# 使用 LMDeploy 加速评测推理
VLMEvalKit 支持测试由 LMDeploy 部署的 VLM 模型,下面以 InternVL2-8B 为例,展示如何测试模型
## 第0步 安装 LMDeploy
```bash
pip install lmdeploy
```
其他安装方式可以参考 LMDeploy 的[文档](https://github.com/InternLM/lmdeploy)
## 第1步 启动推理服务
```bash
lmdeploy serve api_server OpenGVLab/InternVL2-8B --model-name InternVL2-8B
```
> [!IMPORTANT]
> 因为 VLMEvalKit 中的模型对于不同数据集在构建 prompt 时可能有自定义行为,如 InternVL2 对于 HallusionBench 的处理,所以,server 端在启动的时候需要指定 `--model-name`,这样在使用 LMDEploy api 时可以根据名字选择合适的 prompt 构建策略。
>
> 如果指定了 `--server-port`,需要设置对应的环境变量 `LMDEPLOY_API_BASE`
## 第2步 评测
```bash
python run.py --data MMStar --model InternVL2-8B --verbose --api-nproc 64
```
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+216
View File
@@ -0,0 +1,216 @@
# 快速开始
在运行评测脚本之前,你需要先**配置** VLMs,并正确设置模型路径。然后你可以使用脚本 `run.py` 进行多个VLMs和基准测试的推理和评估。
## 第0步 安装和设置必要的密钥
**安装**
```bash
git clone https://github.com/open-compass/VLMEvalKit.git
cd VLMEvalKit
pip install -e .
```
**设置密钥**
要使用 API 模型(如 GPT-4v, Gemini-Pro-V 等)进行推理,或使用 LLM API 作为**评判者或选择提取器**,你需要首先设置 API 密钥。如果你设置了密钥,VLMEvalKit 将使用一个评判 LLM 从输出中提取答案,否则它将使用**精确匹配模式**(在输出字符串中查找 "Yes", "No", "A", "B", "C"...)。**精确匹配模式只能应用于是或否任务和多项选择任务。**
- 你可以将所需的密钥放在 `$VLMEvalKit/.env` 中,或直接将它们设置为环境变量。如果你选择创建 `.env` 文件,其内容将如下所示:
```bash
# .env 文件,将其放置在 $VLMEvalKit 下
# 专有 VLMs 的 API 密钥
# QwenVL APIs
DASHSCOPE_API_KEY=
# Gemini w. Google Cloud Backends
GOOGLE_API_KEY=
# OpenAI API
OPENAI_API_KEY=
OPENAI_API_BASE=
# StepAI API
STEPAI_API_KEY=
# REKA API
REKA_API_KEY=
# GLMV API
GLMV_API_KEY=
# CongRong API
CW_API_BASE=
CW_API_KEY=
# SenseNova API
SENSENOVA_API_KEY=
# Hunyuan-Vision API
HUNYUAN_SECRET_KEY=
HUNYUAN_SECRET_ID=
# LMDeploy API
LMDEPLOY_API_BASE=
# 你可以设置一个评估时代理,评估阶段产生的 API 调用将通过这个代理进行
EVAL_PROXY=
```
- 如果需要使用 API 在对应键值空白处填写上你的密钥。这些 API 密钥将在进行推理和评估时自动加载。
## 第1步 配置
**VLM 配置**:所有 VLMs 都在 `vlmeval/config.py` 中配置。对于某些 VLMs(如 MiniGPT-4、LLaVA-v1-7B),需要额外的配置(在配置文件中配置代码 / 模型权重根目录)。在评估时,你应该使用 `vlmeval/config.py` 中 `supported_VLM` 指定的模型名称来选择 VLM。确保在开始评估之前,你可以成功使用 VLM 进行推理,使用以下命令 `vlmutil check {MODEL_NAME}`。
## 第2步 评测
**新功能!!!** 我们集成了一个新的配置系统,以实现更灵活的评估设置。查看[文档](/docs/zh-CN/ConfigSystem.md)或运行`python run.py --help`了解更多详情 🔥🔥🔥
我们使用 `run.py` 进行评估。你可以使用 `$VLMEvalKit/run.py` 或创建脚本的软链接运行(以便在任何地方使用该脚本):
**参数**
- `--data (list[str])`: 设置在 VLMEvalKit 中支持的数据集名称(可以在代码库首页的 README 中找到支持的数据集列表)
- `--model (list[str])`: 设置在 VLMEvalKit 中支持的 VLM 名称(在 `vlmeval/config.py` 中的 `supported_VLM` 中定义)
- `--mode (str, 默认值为 'all', 可选值为 ['all', 'infer'])`:当 mode 设置为 "all" 时,将执行推理和评估;当设置为 "infer" 时,只执行推理
- `--api-nproc (int, 默认值为 4)`: 调用 API 的线程数
- `--work-dir (str, default to '.')`: 存放测试结果的目录
**用于评测图像多模态评测集的命令**
你可以使用 `python` 或 `torchrun` 来运行脚本:
```bash
# 使用 `python` 运行时,只实例化一个 VLM,并且它可能使用多个 GPU。
# 这推荐用于评估参数量非常大的 VLMs(如 IDEFICS-80B-Instruct)。
# 在 MMBench_DEV_EN、MME 和 SEEDBench_IMG 上使用 IDEFICS-80B-Instruct 进行推理和评估
python run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct --verbose
# 在 MMBench_DEV_EN、MME 和 SEEDBench_IMG 上使用 IDEFICS-80B-Instruct 仅进行推理
python run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct --verbose --mode infer
# 使用 `torchrun` 运行时,每个 GPU 上实例化一个 VLM 实例。这可以加快推理速度。
# 但是,这仅适用于消耗少量 GPU 内存的 VLMs。
# 在 MMBench_DEV_EN、MME 和 SEEDBench_IMG 上使用 IDEFICS-9B-Instruct、Qwen-VL-Chat、mPLUG-Owl2。在具有 8 个 GPU 的节点上进行推理和评估。
torchrun --nproc-per-node=8 run.py --data MMBench_DEV_EN MME SEEDBench_IMG --model idefics_80b_instruct qwen_chat mPLUG-Owl2 --verbose
# 在 MME 上使用 Qwen-VL-Chat。在具有 2 个 GPU 的节点上进行推理和评估。
torchrun --nproc-per-node=2 run.py --data MME --model qwen_chat --verbose
```
**用于评测视频多模态评测集的命令**
```bash
# 使用 `python` 运行时,只实例化一个 VLM,并且它可能使用多个 GPU。
# 这推荐用于评估参数量非常大的 VLMs(如 IDEFICS-80B-Instruct)。
# 在 MMBench-Video 上评测 IDEFCIS2-8B, 视频采样 8 帧作为输入,不采用 pack 模式评测. MMBench_Video_8frame_nopack 是一个定义在 `vlmeval/dataset/video_dataset_config.py` 的数据集设定.
torchrun --nproc-per-node=8 run.py --data MMBench_Video_8frame_nopack --model idefics2_8
# 在 MMBench-Video 上评测 GPT-4o (API 模型), 视频采样每秒一帧作为输入,采用 pack 模式评测
python run.py --data MMBench_Video_1fps_pack --model GPT4o
```
评估结果将作为日志打印出来。此外,**结果文件**也会在目录 `$YOUR_WORKING_DIRECTORY/{model_name}` 中生成。以 `.csv` 结尾的文件包含评估的指标。
### 常见问题
#### 构建输入prompt:`build_prompt()`函数
如果您在评测某个benchmark时,发现模型输出的结果与预期不符,可能是因为您使用的模型没有正确构建输入prompt。
在VLMEvalkit中,每个`dataset`类都包含一个名为`build_prompt()`的函数,用于构建输入问题的格式。不同的benchmark可以选择自定义`build_prompt()`函数,也可以使用默认的实现。
例如,在处理默认的[多选题/Multi-Choice QA]([vlmeval/dataset/image_mcq.py](https://github.com/open-compass/VLMEvalKit/blob/43af13e052de6805a8b08cd04aed5e0d74f82ff5/vlmeval/dataset/image_mcq.py#L164))时,`ImageMCQDataset.build_prompt()`类会将`hint`、`question`、`options`等元素(若数据集中包含)组合成一个完整的问题格式,如下所示:
```
HINT
QUESTION
Options:
A. Option A
B. Option B
···
Please select the correct answer from the options above.
```
此外,由于不同模型对评测的需求可能有所不同,VLMEvalkit也支持在模型层面自定义对不同benchmark构建prompt的方法,即`model.build_prompt()`,具体示例可以参考[InternVL](https://github.com/open-compass/VLMEvalKit/blob/43af13e052de6805a8b08cd04aed5e0d74f82ff5/vlmeval/vlm/internvl_chat.py#L324)。
**注意:当同时定义了`model.build_prompt()`以及`dataset.build_prompt()`时,`model.build_prompt()`将优先于`dataset.build_prompt()`,即前者会覆盖后者。**
由于部分模型(如Qwen2VL,InternVL等)对于不同类型的benchmark定义了广泛的prompt构建方法,为了更灵活地适应不同的benchmark,VLMEvalkit支持在模型中自定义`model.use_custom_prompt()`函数。通过添加或者修改`use_custom_prompt()`函数,您可以决定对于哪些benchmark使用模型自定义的`use_custom_prompt()`方法,示例如下:
```
def use_custom_prompt(self, dataset: str) -> bool:
from vlmeval.dataset import DATASET_TYPE, DATASET_MODALITY
dataset_type = DATASET_TYPE(dataset, default=None)
if not self._use_custom_prompt:
return False
if listinstr(['MMVet'], dataset):
return True
if dataset_type == 'MCQ':
return True
if DATASET_MODALITY(dataset) == 'VIDEO':
return False
return False
```
仅当`use_custom_prompt()`函数返回`True`时,VLMEvalkit才会对当前benchmark调用模型的`build_prompt()`函数。
通过这种方式,您可以根据具体需求灵活地控制哪些benchmark使用模型自定义的prompt构建逻辑,从而更好地适配不同模型和任务的需求。
#### 模型切分
目前 VLMEvalKit 的启动方式自动支持同机上进程间 GPU 资源的划分与模型切分。该功能在推理后端为 `lmdeploy` 或 `transformers` 时被支持,具体行为如下:
- 基于 `python` 命令启动时,模型默认分配到所有可用的 GPU 上,如想指定使用哪些 GPU,可以使用 `CUDA_VISIBLE_DEVICES` 环境变量。
- 基于 `torchrun` 命令启动时,每个模型实例会被分配到 `N_GPU // N_PROC` 个 GPU 上,`N_PROC` 为 torchrun 命令中的 `--nproc-per-node` 参数所指定的进程数。`N_GPU` 的取值为:
- 如 `CUDA_VISIBLE_DEVICES` 环境变量未设置,`N_GPU` 为全部可用 GPU 数量。
- 如 `CUDA_VISIBLE_DEVICES` 环境变量被设置,`N_GPU` 为 `CUDA_VISIBLE_DEVICES` 环境变量所指定的 GPU 数量,并且,仅有指定的 GPU 会被利用。
下面提供了,在一台配备 8 块 GPU 的机器上运行评测任务的具体示例:
```bash
# <!-- 起两个模型实例数据并行,每个实例用 4 GPU -->
torchrun --nproc-per-node=2 run.py --data MMBench_DEV_EN --model InternVL3-78B
# <!-- 起一个模型实例,每个实例用 8 GPU -->
python run.py --data MMBench_DEV_EN --model InternVL3-78B
# <!-- 起三个模型实例,每个实例用 2 GPU,0 号、7 号 GPU 未被使用 -->
CUDA_VISIBLE_DEVICES=1,2,3,4,5,6 torchrun --nproc-per-node=3 run.py --data MMBench_DEV_EN --model InternVL3-38B
```
注:此方式不支持 `vllm` 后端,基于 `vllm` 后端起评测任务时,请用 `python` 命令启动,默认调用所有可见的 GPU。
#### 性能差距
在不同的运行环境中,模型的性能表现可能会有所差异。因此,在评估过程中,您可能会发现自己的评测结果与VLMEvalKit官方榜单上的结果存在差距。这种差异可能与`transformers`, `cuda`, `torch`等版本的变化有关。
此外,对于异常的表现,我们建议您优先查看运行完成后的本地生成记录`{model}_{dataset}.xlsx`或者评估记录`{model}_{dataset}_{judge_model}.xlsx`,这可能会帮助您更好地理解评估结果并发现问题。
### 部署本地语言模型作为评判 / 选择提取器
上述默认设置使用 OpenAI 的 GPT 作为评判 LLM。你也可以使用 [LMDeploy](https://github.com/InternLM/lmdeploy) 部署本地评判 LLM。
首先进行安装:
```
pip install lmdeploy openai
```
然后可以通过一行代码部署本地评判 LLM。LMDeploy 将自动从 Huggingface 下载模型。假设我们使用 internlm2-chat-1_8b 作为评判,端口为 23333,密钥为 sk-123456(密钥必须以 "sk-" 开头,后跟任意数字):
```
lmdeploy serve api_server internlm/internlm2-chat-1_8b --server-port 23333
```
使用以下 Python 代码获取由 LMDeploy 注册的模型名称:
```
from openai import OpenAI
client = OpenAI(
api_key='sk-123456',
base_url="http://0.0.0.0:23333/v1"
)
model_name = client.models.list().data[0].id
```
配置对应环境变量,以告诉 VLMEvalKit 如何使用本地评判 LLM。正如上面提到的,也可以在 `$VLMEvalKit/.env` 文件中设置:
```
OPENAI_API_KEY=sk-123456
OPENAI_API_BASE=http://0.0.0.0:23333/v1/chat/completions
LOCAL_LLM=<model_name you get>
```
最后,你可以运行第2步中的命令,使用本地评判 LLM 来评估你的 VLM。
**请注意:**
- 如果你希望将评判 LLM 部署在单独的一个 GPU 上,并且由于 GPU 内存有限而希望在其他 GPU 上评估你的 VLM,可以使用 `CUDA_VISIBLE_DEVICES=x` 这样的方法,例如:
```
CUDA_VISIBLE_DEVICES=0 lmdeploy serve api_server internlm/internlm2-chat-1_8b --server-port 23333
CUDA_VISIBLE_DEVICES=1,2,3 torchrun --nproc-per-node=3 run.py --data HallusionBench --model qwen_chat --verbose
```
- 如果本地评判 LLM 在遵循指令方面不够好,评估过程可能会失败。请通过 issues 报告此类失败情况。
- 可以以不同的方式部署评判 LLM,例如使用私有 LLM(而非来自 HuggingFace)或使用量化 LLM。请参考 [LMDeploy doc](https://lmdeploy.readthedocs.io/en/latest/serving/api_server.html) 文档。也可以使用其他支持 OpenAI API 框架的方法。
### 使用 LMDeploy 加速模型推理
可参考[文档](/docs/zh-CN/EvalByLMDeploy.md)
+131
View File
@@ -0,0 +1,131 @@
<div align="center">
![LOGO](http://opencompass.openxlab.space/utils/MMLB.jpg)
<b>VLMEvalKit: 一种多模态大模型评测工具 </b>
[![][github-contributors-shield]][github-contributors-link] • [![][github-forks-shield]][github-forks-link] • [![][github-stars-shield]][github-stars-link] • [![][github-issues-shield]][github-issues-link] • [![][github-license-shield]][github-license-link]
[English](/README.md) | 简体中文 | [日本語](/docs/ja/README_ja.md)
<a href="https://rank.opencompass.org.cn/leaderboard-multimodal">🏆 OpenCompass 排行榜 </a> •
<a href="#%EF%B8%8F-quickstart">🏗️ 快速开始 </a> •
<a href="#-datasets-models-and-evaluation-results">📊 数据集和模型 </a> •
<a href="#%EF%B8%8F-development-guide">🛠️ 开发指南 </a> •
<a href="#-the-goal-of-vlmevalkit">🎯 我们的目标 </a> •
<a href="#%EF%B8%8F-citation">🖊️ 引用 </a>
<a href="https://huggingface.co/spaces/opencompass/open_vlm_leaderboard">🤗 HuggingFace 排行榜 (存档全部性能) </a> •
<a href="https://huggingface.co/datasets/VLMEval/OpenVLMRecords">🤗 原始评测记录</a> •
<a href="https://discord.gg/evDT4GZmxN">🔊 Discord</a> •
<a href="https://www.arxiv.org/abs/2407.11691">📝 技术报告 </a>
</div>
**VLMEvalKit** (python 包名为 **vlmeval**) 是一款专为大型视觉语言模型 (Large Vision-Language Models, LVLMs) 评测而设计的开源工具包。该工具支持在各种基准测试上对大型视觉语言模型进行**一键评估**,无需进行繁重的数据准备工作,让评估过程更加简便。在 VLMEvalKit 中,我们对所有大型视觉语言模型生成的结果进行评测,并提供基于**精确匹配**与基于 **LLM 的答案提取**两种评测结果。
## 🆕 更新
- **[2025-04-29]** 优化 `torchrun` 启动逻辑:目前 `torchrun` 启动时,若进程数为 M,机器 GPU 卡数为 N,将会自动调整每个进程分配的 GPU 数量为 `N // M`。目前此分配方式适用于 `transformers`, `lmdeploy` 推理后端,`vllm` 推理后端仅支持使用 python 启动 🔥🔥🔥
- **[2025-02-20]** 支持新模型:**InternVL2.5 series, QwenVL2.5 series, QVQ-72B, Doubao-VL, Janus-Pro-7B, MiniCPM-o-2.6, InternVL2-MPO, LLaVA-CoT, Hunyuan-Standard-Vision, Ovis2, Valley, SAIL-VL, Ross, Long-VITA, EMU3, SmolVLM**。支持新基准:**MMMU-Pro, WeMath, 3DSRBench, LogicVista, VL-RewardBench, CC-OCR, CG-Bench, CMMMU, WorldSense**。请参考[**VLMEvalKit Features**](https://aicarrier.feishu.cn/wiki/Qp7wwSzQ9iK1Y6kNUJVcr6zTnPe?table=tblsdEpLieDoCxtb)以获取更多信息。感谢社区的各位贡献者 🔥🔥🔥
- **[2024-11-21]** 集成了一个新的配置系统,以实现更灵活的评估设置。查看[文档](/docs/zh-CN/ConfigSystem.md)或运行`python run.py --help`了解更多详情 🔥🔥🔥
- **[2024-11-21]** 支持 **[QSpatial](https://andrewliao11.github.io/spatial_prompt/)**,一个用于定量空间推理的多模态基准(例如,确定大小/距离),感谢 **[andrewliao11](https://github.com/andrewliao11)** 提供官方支持 🔥🔥🔥
- **[2024-11-21]** 支持 **[MM-Math](https://github.com/kge-sun/mm-math)**,一个包含约6K初中多模态推理数学问题的新多模态数学基准。GPT-4o-20240806在该基准上达到了22.5%的准确率 🔥🔥🔥
- **[2024-11-16]** 支持 **[OlympiadBench](https://github.com/OpenBMB/OlympiadBench)**,一个多模态基准,包含奥林匹克级别的数学和物理问题 🔥🔥🔥
- **[2024-11-16]** 支持 **[WildVision](https://huggingface.co/datasets/WildVision/wildvision-bench)**,一个基于多模态竞技场数据的主观多模态基准 🔥🔥🔥
- **[2024-11-13]** 支持 **[MIA-Bench](https://arxiv.org/abs/2407.01509)**,一个多模态指令跟随基准 🔥🔥🔥
- **[2024-11-08]** 支持 **[Aria](https://arxiv.org/abs/2410.05993)**,一个多模态原生 MoE 模型,感谢 **[teowu](https://github.com/teowu)** 🔥🔥🔥
- **[2024-11-04]** 支持 **[WorldMedQA-V](https://www.arxiv.org/abs/2410.12722)**,该基准包含 1000 多个医学 VQA 问题,涵盖巴西、以色列、日本、西班牙等四个国家的语言,以及它们的英文翻译 🔥🔥🔥
## 🏗️ 快速开始 <a id="quickstart"></a>
请参阅[**快速开始**](/docs/zh-CN/Quickstart.md)获取入门指南。
## 📊 评测结果,支持的数据集和模型 <a id="data-model-results"></a>
### 评测结果
**[OpenVLM Leaderboard](https://huggingface.co/spaces/opencompass/open_vlm_leaderboard)**: **[下载全部细粒度测试结果](http://opencompass.openxlab.space/assets/OpenVLM.json)**.
请查看[**VLMEvalKit Features**](https://aicarrier.feishu.cn/wiki/Qp7wwSzQ9iK1Y6kNUJVcr6zTnPe?table=tblsdEpLieDoCxtb)中的 **Supported Benchmarks** 标签,以查看所有支持的图像和视频基准(70+)。
请查看[**VLMEvalKit Features**](https://aicarrier.feishu.cn/wiki/Qp7wwSzQ9iK1Y6kNUJVcr6zTnPe?table=tblsdEpLieDoCxtb)中的 **Supported LMMs** 标签,以查看所有支持的 LMMs,包括商业 API、开源模型等(200+)。
### 其他
**Transformers 的版本推荐:**
**请注意**,某些 VLM 可能无法在某些特定的 transformers 版本下运行,我们建议使用以下设置来评估对应的VLM:
- **请用** `transformers==4.33.0` **来运行**: `Qwen series`, `Monkey series`, `InternLM-XComposer Series`, `mPLUG-Owl2`, `OpenFlamingo v2`, `IDEFICS series`, `VisualGLM`, `MMAlaya`, `ShareCaptioner`, `MiniGPT-4 series`, `InstructBLIP series`, `PandaGPT`, `VXVERSE`.
- **请用** `transformers==4.37.0 ` **来运行**: `LLaVA series`, `ShareGPT4V series`, `TransCore-M`, `LLaVA (XTuner)`, `CogVLM Series`, `EMU2 Series`, `Yi-VL Series`, `MiniCPM-[V1/V2]`, `OmniLMM-12B`, `DeepSeek-VL series`, `InternVL series`, `Cambrian Series`, `VILA Series`, `Llama-3-MixSenseV1_1`, `Parrot-7B`, `PLLaVA Series`.
- **请用** `transformers==4.40.0 ` **来运行**: `IDEFICS2`, `Bunny-Llama3`, `MiniCPM-Llama3-V2.5`, `360VL-70B`, `Phi-3-Vision`, `WeMM`.
- **请用** `transformers==4.42.0 ` **来运行**: `AKI`.
- **请用** `transformers==latest` **来运行**: `LLaVA-Next series`, `PaliGemma-3B`, `Chameleon series`, `Video-LLaVA-7B-HF`, `Ovis series`, `Mantis series`, `MiniCPM-V2.6`, `OmChat-v2.0-13B-sinlge-beta`, `Idefics-3`, `GLM-4v-9B`, `VideoChat2-HD`.
**如何测试一个 VLM 是否可以正常运行:**
```python
from vlmeval.config import supported_VLM
model = supported_VLM['idefics_9b_instruct']()
# 前向单张图片
ret = model.generate(['assets/apple.jpg', 'What is in this image?'])
print(ret) # 这张图片上有一个带叶子的红苹果
# 前向多张图片
ret = model.generate(['assets/apple.jpg', 'assets/apple.jpg', 'How many apples are there in the provided images? '])
print(ret) # 提供的图片中有两个苹果
```
## 🛠️ 开发指南 <a id="development"></a>
要开发自定义评测数据集,支持其他 VLMs,或为 VLMEvalKit 贡献代码,请参阅[**开发指南**](/docs/zh-CN/Development_zh-CN.md)。
为激励来自社区的共享并分享相应的 credit,在下一次 report 更新中,我们将:
- 致谢所有的 contribution
- 具备三个或以上主要贡献 (支持新模型、评测集、或是主要特性) 的贡献者将可以加入技术报告的作者列表 。合条件的贡献者可以创建 issue 或是在 [VLMEvalKit Discord Channel](https://discord.com/invite/evDT4GZmxN) 私信 kennyutc,我们将进行跟进
## 🎯 VLMEvalKit 的目标 <a id="goal-of-vlmevalkit"></a>
**该代码库的设计目标是:**
1. 提供一个**易于使用**的**开源评估工具包**,方便研究人员和开发人员评测现有的多模态大模型,并使评测结果**易于复现**。
2. 使 VLM 开发人员能够轻松地评测自己的模型。在多个支持的基准测试上评估 VLM,只需实现一个 `generate_inner()` 函数,所有其他工作负载(数据下载、数据预处理、预测推理、度量计算)都由代码库处理。
**该代码库的设计目标不是:**
复现所有**第三方基准测试**原始论文中报告的准确数字。有两个相关的原因:
1. VLMEvalKit 对所有 VLMs 使用基于生成的评估(可选使用基于 LLM 的答案提取)。同时,一些基准测试可能官方使用不同的方法(*例如,SEEDBench 使用基于 PPL 的评估*)。对于这些基准测试,我们在相应的结果中比较两个得分。我们鼓励开发人员在代码库中支持其他评估范式。
2. 默认情况下,我们对所有多模态模型使用相同的提示模板来评估基准测试。同时,**一些多模态模型可能有他们特定的提示模板**(目前可能未在代码库中涵盖)。我们鼓励 VLM 的开发人员在 VLMEvalKit 中实现自己的提示模板,如果目前未覆盖。这将有助于提高可复现性。
## 🖊️ 引用 <a id="citation"></a>
如果我们的工作对您有所帮助,请考虑 **star🌟** VLMEvalKit。感谢支持!
[![Stargazers repo roster for @open-compass/VLMEvalKit](https://reporoster.com/stars/open-compass/VLMEvalKit)](https://github.com/open-compass/VLMEvalKit/stargazers)
如果您在研究中使用了 VLMEvalKit,或希望参考已发布的开源评估结果,请使用以下 BibTeX 条目以及与您使用的特定 VLM / 基准测试相对应的 BibTex 条目。
```bib
@misc{duan2024vlmevalkit,
title={VLMEvalKit: An Open-Source Toolkit for Evaluating Large Multi-Modality Models},
author={Haodong Duan and Junming Yang and Yuxuan Qiao and Xinyu Fang and Lin Chen and Yuan Liu and Xiaoyi Dong and Yuhang Zang and Pan Zhang and Jiaqi Wang and Dahua Lin and Kai Chen},
year={2024},
eprint={2407.11691},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2407.11691},
}
```
<p align="right"><a href="#top">🔝回到顶部</a></p>
[github-contributors-link]: https://github.com/open-compass/VLMEvalKit/graphs/contributors
[github-contributors-shield]: https://img.shields.io/github/contributors/open-compass/VLMEvalKit?color=c4f042&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/open-compass/VLMEvalKit/network/members
[github-forks-shield]: https://img.shields.io/github/forks/open-compass/VLMEvalKit?color=8ae8ff&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/open-compass/VLMEvalKit/issues
[github-issues-shield]: https://img.shields.io/github/issues/open-compass/VLMEvalKit?color=ff80eb&labelColor=black&style=flat-square
[github-license-link]: https://github.com/open-compass/VLMEvalKit/blob/main/LICENSE
[github-license-shield]: https://img.shields.io/github/license/open-compass/VLMEvalKit?color=white&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/open-compass/VLMEvalKit/stargazers
[github-stars-shield]: https://img.shields.io/github/stars/open-compass/VLMEvalKit?color=ffcb47&labelColor=black&style=flat-square
@@ -0,0 +1,63 @@
.header-logo {
background-image: url("../image/logo.svg");
background-size: 275px 80px;
height: 80px;
width: 275px;
}
@media screen and (min-width: 1100px) {
.header-logo {
top: -25px;
}
}
pre {
white-space: pre;
}
@media screen and (min-width: 2000px) {
.pytorch-content-left {
width: 1200px;
margin-left: 30px;
}
article.pytorch-article {
max-width: 1200px;
}
.pytorch-breadcrumbs-wrapper {
width: 1200px;
}
.pytorch-right-menu.scrolling-fixed {
position: fixed;
top: 45px;
left: 1580px;
}
}
article.pytorch-article section code {
padding: .2em .4em;
background-color: #f3f4f7;
border-radius: 5px;
}
/* Disable the change in tables */
article.pytorch-article section table code {
padding: unset;
background-color: unset;
border-radius: unset;
}
table.autosummary td {
width: 50%
}
img.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
article.pytorch-article p.rubric {
font-weight: bold;
}
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" version="1.1" width="210" height="36" viewBox="0 0 1920 480" xml:space="preserve">
<desc>Created with Fabric.js 5.3.0</desc>
<defs>
</defs>
<g transform="matrix(8.6096948697 0 0 8.6096948697 283.4607944077 326.096948697)" id="2rbaYufxVtcDPCyBcyhLL" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(88,120,180); fill-rule: nonzero; opacity: 1;" transform=" translate(-19.1, -28)" d="M 16.5 22.6 L 10.1 25.700000000000003 L 15.399999999999999 25.500000000000004 L 16.5 22.6 z M 12.3 33.6 L 13.4 30.700000000000003 L 8.100000000000001 30.900000000000002 L 12.3 33.6 z M 21.6 33.3 L 28 30.199999999999996 L 22.7 30.399999999999995 L 21.6 33.3 z M 25.8 22.4 L 24.7 25.299999999999997 L 30 25.099999999999998 L 25.8 22.4 z M 31.5 26.2 L 24.4 26.4 L 22.7 25.299999999999997 L 24.2 21.299999999999997 L 22.2 20 L 19 21.5 L 17.5 25.4 L 14.8 26.7 L 7.700000000000001 26.9 L 4.500000000000001 28.4 L 6.600000000000001 29.799999999999997 L 13.700000000000001 29.599999999999998 L 13.700000000000001 29.599999999999998 L 15.4 30.7 L 13.9 34.7 L 16 36 L 19.2 34.5 L 20.7 30.6 L 20.7 30.6 L 23.3 29.400000000000002 L 23.3 29.400000000000002 L 30.5 29.200000000000003 L 33.7 27.700000000000003 L 31.5 26.2 z M 20.2 28.7 C 19.2 29.2 17.9 29.2 17.2 28.8 C 16.599999999999998 28.400000000000002 16.8 27.6 17.8 27.2 C 18.8 26.7 20.1 26.7 20.8 27.099999999999998 C 21.5 27.5 21.2 28.2 20.2 28.7 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 351.9078686218 195.2295866776)" id="Gj0NH9qgtM_hm6hdZ_Tf1" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(54,86,155); fill-rule: nonzero; opacity: 1;" transform=" translate(-27.05, -12.8)" d="M 33.5 19.8 L 32.2 13.3 L 30.700000000000003 15.200000000000001 L 33.5 19.8 z M 27.5 5.1 L 23.3 2.3999999999999995 L 26 7 L 27.5 5.1 z M 20.7 5.7 L 22 12.2 L 23.5 10.299999999999999 L 20.7 5.7 z M 26.8 20.4 L 31 23.099999999999998 L 28.3 18.5 L 26.8 20.4 z M 34 22.3 L 30.4 16.1 L 30.4 16.1 L 29.9 13.400000000000002 L 31.9 10.800000000000002 L 31.299999999999997 7.600000000000002 L 29.199999999999996 6.200000000000003 L 27.199999999999996 8.800000000000002 L 25.499999999999996 7.700000000000003 L 21.799999999999997 1.400000000000003 L 19.6 0 L 20.200000000000003 3.2 L 23.900000000000002 9.5 L 23.900000000000002 9.5 L 24.400000000000002 12.1 L 24.400000000000002 12.1 L 22.400000000000002 14.7 L 23.000000000000004 17.9 L 25.100000000000005 19.299999999999997 L 27.000000000000004 16.799999999999997 L 28.700000000000003 17.9 L 32.400000000000006 24.2 L 34.50000000000001 25.599999999999998 L 34 22.3 z M 27.5 14.6 C 26.9 14.2 26.2 13 26 12 C 25.8 11 26.2 10.5 26.8 10.9 C 27.400000000000002 11.3 28.1 12.5 28.3 13.5 C 28.5 14.6 28.1 15.1 27.5 14.6 z" stroke-linecap="round" />
</g>
<g transform="matrix(8.6096948697 0 0 8.6096948697 209.8479032717 200.3954035994)" id="lmxdEhRpowSXVKC1LScVi" >
<path style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1;" transform=" translate(-10.55, -13.4)" d="M 12 2.8 L 5.6 5.9 L 9.399999999999999 7.6000000000000005 L 12 2.8 z M 1.1 14.4 L 2.4000000000000004 20.9 L 5 16.099999999999998 L 1.1 14.4 z M 9.1 24 L 15.5 20.9 L 11.7 19.2 L 9.1 24 z M 20 12.4 L 18.7 5.9 L 16.099999999999998 10.7 L 20 12.4 z M 20.4 14.9 L 15.299999999999999 12.600000000000001 L 15.299999999999999 12.600000000000001 L 14.799999999999999 9.900000000000002 L 18.299999999999997 3.400000000000002 L 17.699999999999996 0.20000000000000195 L 14.499999999999996 1.700000000000002 L 11 8.1 L 8.3 9.4 L 8.3 9.4 L 3.2 7.1 L 0 8.6 L 0.6 11.8 L 5.8 14.100000000000001 L 6.3 16.8 L 6.3 16.8 L 2.8 23.4 L 3.4 26.599999999999998 L 6.6 25.099999999999998 L 10.1 18.599999999999998 L 12.7 17.4 L 12.7 17.4 L 17.9 19.799999999999997 L 21.099999999999998 18.299999999999997 L 20.4 14.9 z M 10.9 15.2 C 9.9 15.7 9 15.2 8.8 14.2 C 8.600000000000001 13.2 9.200000000000001 12 10.200000000000001 11.5 C 11.200000000000001 11 12.100000000000001 11.5 12.3 12.5 C 12.5 13.5 11.9 14.7 10.9 15.2 z" stroke-linecap="round" />
</g>
<g transform="matrix(1 0 0 1 1109.6072390741 240)" style="" id="IiDed4ej1oioRNDwSqAwf">
<text xml:space="preserve" font-family="Amethysta" font-size="225" font-style="normal" font-weight="normal" line-height="1" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(27,56,130); fill-rule: nonzero; opacity: 1; white-space: pre;"><tspan x="-714.0188713264" y="72.3065" style="white-space: pre; "> VLMEvalKit</tspan></text>
<style>
@font-face {
font-family: "Amethysta";
font-weight: normal;
src: url("data:font/ttf;base64,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 truncated
}
</style></g></svg>

After

Width:  |  Height:  |  Size: 87 KiB

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="_图层_2" data-name="图层 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 34.59 36">
<defs>
<style>
.cls-1 {
fill: #36569b;
}
.cls-2 {
fill: #1b3882;
}
.cls-3 {
fill: #5878b4;
}
</style>
</defs>
<g id="_图层_1-2" data-name="图层 1">
<g>
<g id="_3" data-name="3">
<path class="cls-3" d="m16.53,22.65l-6.37,3.07,5.27-.16,1.1-2.91Zm-4.19,10.95l1.12-2.91-5.27.17,4.15,2.74Zm9.3-.29l6.37-3.07-5.27.16-1.1,2.91Zm4.19-10.95l-1.12,2.91,5.27-.17-4.15-2.74Zm5.72,3.81l-7.08.23-1.73-1.14,1.5-3.95-2.06-1.36-3.16,1.53-1.48,3.89-2.67,1.29-7.14.23-3.16,1.53,2.07,1.36,7.13-.23h0s1.69,1.11,1.69,1.11l-1.51,3.98,2.06,1.36,3.16-1.53,1.5-3.95h0s2.56-1.24,2.56-1.24h0s7.23-.24,7.23-.24l3.16-1.53-2.06-1.36Zm-11.29,2.56c-.99.48-2.31.52-2.96.1-.65-.42-.37-1.15.62-1.63.99-.48,2.31-.52,2.96-.1.65.42.37,1.15-.62,1.63Z"/>
</g>
<g id="_2" data-name="2">
<path class="cls-1" d="m33.5,19.84l-1.26-6.51-1.46,1.88,2.72,4.63Zm-6.05-14.69l-4.16-2.74,2.71,4.64,1.45-1.89Zm-6.73.58l1.26,6.51,1.46-1.88-2.72-4.63Zm6.05,14.69l4.16,2.74-2.71-4.64-1.45,1.89Zm7.19,1.91l-3.63-6.2h0s-.53-2.74-.53-2.74l1.96-2.56-.63-3.23-2.07-1.36-1.96,2.56-1.69-1.11-3.71-6.33-2.07-1.36.63,3.23,3.68,6.28h0s.51,2.62.51,2.62h0s-1.99,2.6-1.99,2.6l.63,3.23,2.06,1.36,1.95-2.54,1.73,1.14,3.69,6.29,2.07,1.36-.63-3.23Zm-6.47-7.7c-.65-.42-1.33-1.59-1.52-2.6-.2-1.01.17-1.49.81-1.06.65.42,1.33,1.59,1.52,2.6.2,1.01-.17,1.49-.81,1.06Z"/>
</g>
<g id="_1" data-name="1">
<path class="cls-2" d="m11.96,2.82l-6.37,3.07,3.81,1.74,2.55-4.81ZM1.07,14.37l1.26,6.53,2.56-4.8-3.82-1.73Zm7.99,9.59l6.37-3.07-3.81-1.74-2.55,4.81Zm10.89-11.55l-1.26-6.53-2.56,4.8,3.82,1.73Zm.45,2.53l-5.13-2.32h0s-.53-2.71-.53-2.71l3.47-6.53-.63-3.24-3.16,1.53-3.42,6.43-2.67,1.29h0s-5.17-2.34-5.17-2.34l-3.16,1.53.63,3.24,5.17,2.33.51,2.65h0s-3.49,6.57-3.49,6.57l.63,3.24,3.16-1.53,3.46-6.52,2.56-1.24h0s5.24,2.37,5.24,2.37l3.16-1.53-.63-3.24Zm-9.52.24c-.99.48-1.95.04-2.14-.97-.2-1.01.44-2.22,1.43-2.69.99-.48,1.95-.04,2.14.97.2,1.01-.44,2.22-1.43,2.7Z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -0,0 +1,10 @@
var collapsedSections = [];
$(document).ready(function () {
$('.model-summary').DataTable({
"stateSave": false,
"lengthChange": false,
"pageLength": 20,
"order": []
});
});
@@ -0,0 +1,18 @@
{% extends "layout.html" %}
{% block body %}
<h1>Page Not Found</h1>
<p>
The page you are looking for cannot be found.
</p>
<p>
If you just switched documentation versions, it is likely that the page you were on is moved. You can look for it in
the content table left, or go to <a href="{{ pathto(root_doc) }}">the homepage</a>.
</p>
<!-- <p>
If you cannot find documentation you want, please <a
href="">open an issue</a> to tell us!
</p> -->
{% endblock %}
@@ -0,0 +1,13 @@
.. role:: hidden
:class: hidden-section
.. currentmodule:: {{ module }}
{{ name | underline}}
.. autoclass:: {{ name }}
:members:
..
autogenerated from _templates/autosummary/class.rst
note it does not have :inherited-members:
@@ -0,0 +1,14 @@
.. role:: hidden
:class: hidden-section
.. currentmodule:: {{ module }}
{{ name | underline}}
.. autoclass:: {{ name }}
:members:
:special-members: __call__
..
autogenerated from _templates/callable.rst
note it does not have :inherited-members:
+242
View File
@@ -0,0 +1,242 @@
# flake8: noqa
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import ast
import subprocess
import sys
import pytorch_sphinx_theme
from sphinx.builders.html import StandaloneHTMLBuilder
sys.path.insert(0, os.path.abspath('../../'))
# -- Project information -----------------------------------------------------
project = 'VLMEvalKit'
copyright = '2023, VLMEvalKit'
author = 'VLMEvalKit Authors'
# The full version, including alpha/beta/rc tags
version_file = '../../vlmeval/__init__.py'
def get_version():
with open(version_file, 'r') as f:
file_content = f.read()
# Parse the file content into an abstract syntax tree (AST)
tree = ast.parse(file_content, filename=version_file)
# Iterate through the body of the AST, looking for an assignment to __version__
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == '__version__':
return node.value.s
raise ValueError('__version__ not found')
release = get_version()
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'myst_parser',
'sphinx_copybutton',
'sphinx_tabs.tabs',
'notfound.extension',
'sphinxcontrib.jquery',
'sphinx_design',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = {
'.rst': 'restructuredtext',
'.md': 'markdown',
}
language = 'cn'
# The master toctree document.
root_doc = 'index'
html_context = {
'github_version': 'latest',
}
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'pytorch_sphinx_theme'
html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# yapf: disable
html_theme_options = {
'menu': [
{
'name': 'GitHub',
'url': 'https://github.com/open-compass/VLMEvalKit'
},
],
# Specify the language of shared menu
'menu_lang': 'cn',
# Disable the default edit on GitHub
'default_edit_on_github': False,
}
# yapf: enable
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = [
'https://cdn.datatables.net/v/bs4/dt-1.12.1/datatables.min.css',
'css/readthedocs.css'
]
html_js_files = [
'https://cdn.datatables.net/v/bs4/dt-1.12.1/datatables.min.js',
'js/custom.js'
]
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'vlmevalkitdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(root_doc, 'vlmevalkit.tex', 'VLMEvalKit Documentation', author,
'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(root_doc, 'vlmevalkit', 'VLMEvalKit Documentation', [author],
1)]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(root_doc, 'vlmevalkit', 'VLMEvalKit Documentation', author,
'VLMEvalKit Authors', 'AGI evaluation toolbox and benchmark.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# set priority when building html
StandaloneHTMLBuilder.supported_image_types = [
'image/svg+xml', 'image/gif', 'image/png', 'image/jpeg'
]
# -- Extension configuration -------------------------------------------------
# Ignore >>> when copying code
copybutton_prompt_text = r'>>> |\.\.\. '
copybutton_prompt_is_regexp = True
# Auto-generated header anchors
myst_heading_anchors = 3
# Enable "colon_fence" extension of myst.
myst_enable_extensions = ['colon_fence', 'dollarmath']
# Configuration for intersphinx
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'numpy': ('https://numpy.org/doc/stable', None),
'torch': ('https://pytorch.org/docs/stable/', None),
'mmengine': ('https://mmengine.readthedocs.io/en/latest/', None),
'transformers':
('https://huggingface.co/docs/transformers/main/en/', None),
}
napoleon_custom_sections = [
# Custom sections for data elements.
('Meta fields', 'params_style'),
('Data fields', 'params_style'),
]
# Disable docstring inheritance
autodoc_inherit_docstrings = False
# Mock some imports during generate API docs.
autodoc_mock_imports = ['rich', 'attr', 'einops']
# Disable displaying type annotations, these can be very verbose
autodoc_typehints = 'none'
# The not found page
notfound_template = '404.html'
def builder_inited_handler(app):
subprocess.run(['./cp_origin_docs.sh'])
def setup(app):
app.connect('builder-inited', builder_inited_handler)
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Copy *.md files from docs/ if it doesn't have a Chinese translation
for filename in $(find ../en/ -name '*.md' -printf "%P\n");
do
mkdir -p $(dirname $filename)
cp -n ../en/$filename ./$filename
done
+2
View File
@@ -0,0 +1,2 @@
[html writers]
table_style: colwidths-auto
+49
View File
@@ -0,0 +1,49 @@
欢迎来到 VLMEvalKit 中文教程!
==========================================
VLMEvalKit 上手路线
-------------------------------
为了用户能够快速上手,我们推荐以下流程:
- 对于想要使用 VLMEvalKit 的用户,我们推荐先阅读 开始你的第一步_ 部分来设置环境,并启动一个迷你实验熟悉流程。
- 若您想进行更多模块的自定义,例如增加数据集和模型,我们提供了 进阶教程_ 。
我们始终非常欢迎用户的 PRs 和 Issues 来完善 VLMEvalKit!
.. _快速开始:
.. toctree::
:maxdepth: 1
:caption: 快速开始
Quickstart.md
.. .. _教程:
.. .. toctree::
.. :maxdepth: 1
.. :caption: 教程
.. user_guides/framework_overview.md
.. _进阶教程:
.. toctree::
:maxdepth: 1
:caption: 进阶教程
Development.md
ConfigSystem.md
.. .. _其他说明:
.. .. toctree::
.. :maxdepth: 1
.. :caption: 其他说明
.. notes/contribution_guide.md
索引与表格
==================
* :ref:`genindex`
* :ref:`search`
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
set -e
set -x
cd ./eval/vlmevalkit
export LMDEPLOY_API_KEY="kunlun"
export LMDEPLOY_API_BASE="http://127.0.0.1:8000/v1/chat/completions"
LOG_DIR="logs"
MODEL_NAME="Skywork-R1V3"
mkdir -p "$LOG_DIR/$MODEL_NAME"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$LOG_DIR/$MODEL_NAME/bench_${TIMESTAMP}.log"
echo "Starting evaluation at $(date)" | tee -a "$LOG_FILE"
# if first argument is empty, use default
if [ -z "$1" ]; then
echo "⚠️ [INFO] No benchmark specified, defaulting to MMMU_DEV_VAL." | tee -a "$LOG_FILE"
echo "👉 To evaluate on other benchmarks, run:"
echo ' bash run_eval.sh "MMMU_DEV_VAL MathVista_MINI HallusionBench ..."'
DATA_ARGS="MMMU_DEV_VAL"
else
DATA_ARGS="$1"
fi
USE_COT=1 python run.py \
--data $DATA_ARGS \
--model R1V3-alpha \
--verbose \
--reuse \
--work-dir ./outputs/$MODEL_NAME \
--judge gpt-4o-2024-05-13 \
--api-nproc 200 2>&1 | tee -a "$LOG_FILE" &
PID=$!
echo "Evaluation process started with PID: $PID" | tee -a "$LOG_FILE"
wait $PID
if [ $? -eq 0 ]; then
echo "Evaluation completed successfully at $(date)" | tee -a "$LOG_FILE"
else
echo "Evaluation failed at $(date)" | tee -a "$LOG_FILE"
exit 1
fi
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
# 设置错误时退出
export LMUData=./eval/vlmevalkit/eval_shell/LMUData
cd ./eval/vlmevalkit
set -e
#sleep 1h
export LMDEPLOY_API_KEY="kunlun"
export LMDEPLOY_API_BASE="http://127.0.0.1:8000/v1/chat/completions"
# 创建日志目录
LOG_DIR="logs"
MODEL_NAME="Skywork_R1V3"
mkdir -p $LOG_DIR/$MODEL_NAME
# 生成带时间戳的日志文件名
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$LOG_DIR/$MODEL_NAME/phyx_eval_${TIMESTAMP}.log"
# 记录开始时间
echo "Starting PHYX evaluation at $(date)" | tee -a "$LOG_FILE"
# 运行评估脚本
USE_COT=0 python run_phyx.py \
--data PHYX \
--model R1V3-alpha \
--verbose \
--reuse \
--work-dir ./outputs/$MODEL_NAME \
--judge gpt-4o-2024-05-13 \
--api-nproc 200 2>&1 | tee -a "$LOG_FILE" &
# 获取后台进程ID
PID=$!
# 记录进程ID
echo "Evaluation process started with PID: $PID" | tee -a "$LOG_FILE"
# 等待进程完成
wait $PID
# 检查进程退出状态
if [ $? -eq 0 ]; then
echo "Evaluation completed successfully at $(date)" | tee -a "$LOG_FILE"
else
echo "Evaluation failed at $(date)" | tee -a "$LOG_FILE"
exit 1
fi
@@ -0,0 +1,4 @@
set -x
MODEL_PATH=/path/to/r1v3-model
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m vllm.entrypoints.openai.api_server --model $MODEL_PATH --port 8000 --trust-remote-code --max_model_len 32768 --served-model-name r1v3-alpha --limit-mm-per-prompt "image=60" --gpu_memory_utilization 0.8 --tensor-parallel-size 8 --dtype auto
@@ -0,0 +1,128 @@
import openai
import os
import json
import time
import re
import pandas as pd
from tqdm import tqdm
from tenacity import retry, wait_random_exponential, stop_after_attempt
def format_prompt(item):
base_prompt = """...(略)...""" # 和原来的base_prompt保持一致,可保留不变
choices_parts = [f"{opt}. {item[opt]}" for opt in ['A', 'B', 'C', 'D'] if opt in item and pd.notna(item[opt])]
choices_str = "\n".join(choices_parts) if choices_parts else "无选项"
prompt = (
f"#问题#\n{item['question']}\n\n"
f"#选项#\n{choices_str}\n\n"
f"#AI回答#\n{item['prediction']}\n\n"
f"#标准答案#\n{item['answer']}\n\n"
f"{base_prompt}"
)
return prompt
def rule_based_evaluation(item):
prediction = str(item['prediction'])
answer = str(item['answer']).strip()
boxed_matches = re.findall(r'\\boxed\{(.*?)\}', prediction)
if not boxed_matches:
return False, ""
last_boxed = boxed_matches[-1].strip()
def normalize(s):
s = re.sub(r'\$|\\[a-z]+|\s+', '', s)
s = re.sub(r'^\{|\}$', '', s)
return s.lower()
if last_boxed == answer or normalize(last_boxed) == normalize(answer):
return True, f"规则匹配:预测的 \\boxed{{{last_boxed}}} 与标准答案 '{answer}' 一致"
return False, ""
def clean_json_response(response):
return re.sub(r'```json|```', '', response).strip()
def process_one(item):
# if not str(item['id']).startswith('val'):
# return item
rule_match, explanation = rule_based_evaluation(item)
if rule_match:
item["is_correct"] = True
item["explanation"] = explanation
item["gpt_score"] = "规则匹配成功,跳过GPT评分"
return item
item["gpt_score"] = ""
item["is_correct"] = False
item["explanation"] = "评分请求失败"
return item
def calculate_accuracy(jsonl_path):
correct, total, original_hit, rule_matched = 0, 0, 0, 0
# single_total,single_acc=0,0
with open(jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
data = json.loads(line)
total += 1
if data.get('is_correct'):
correct += 1
if data.get('hit', 0) == 1:
original_hit += 1
if "规则匹配" in data.get('explanation', '') and data.get('is_correct', False):
if data.get('hit', 0) == 0:
rule_matched += 1
if total > 0:
print(f"\n正确率统计:")
print(f"- 总dev数据量: {total}")
print(f"- 正确数量: {correct} (准确率: {correct / total * 100:.2f}%)")
print(f"- 原始hit=1数量: {original_hit} ({original_hit / total * 100:.2f}%)")
print(f"- 规则匹配补正数量: {rule_matched} ({rule_matched / total * 100:.2f}%)")
else:
print("无可统计数据")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='评估AI回答的准确性')
parser.add_argument('--input', type=str, default='')
parser.add_argument('--output', type=str, default='./eval/vlmevalkit/outputs/Skywork-R1V3/R1V3-alpha/R1V3-alpha_logicvista_gpt4o_rule_based.jsonl')
args = parser.parse_args()
df = pd.read_excel(args.input)
data = df.to_dict('records')
with open(args.output, 'w', encoding='utf-8') as f_out:
for item in tqdm(data):
processed = process_one(item)
f_out.write(json.dumps(processed, ensure_ascii=False) + '\n')
f_out.flush()
calculate_accuracy(args.output)
print("任务完成,结果已写入文件。")
from openpyxl import Workbook
# 分类样本收集
hit0_rule_correct = []
hit1_rule_wrong = []
with open(args.output, 'r', encoding='utf-8') as f_in:
for line in f_in:
processed = json.loads(line)
is_correct = processed.get('is_correct', False)
explanation = processed.get('explanation', '')
hit = processed.get('hit')
if hit == 0 and is_correct and "规则匹配" in explanation:
hit0_rule_correct.append(processed)
elif hit == 1 and (not is_correct or "规则匹配" not in explanation):
hit1_rule_wrong.append(processed)
def save_to_excel(data_list, output_path):
if not data_list:
print(f"无数据可写入 {output_path}")
return
df_out = pd.DataFrame(data_list)
df_out.to_excel(output_path, index=False)
print(f"写入完成:{output_path}")
base_dir = os.path.dirname(args.output)
save_to_excel(hit0_rule_correct, os.path.join(base_dir, 'hit0_rule_matched.xlsx'))
save_to_excel(hit1_rule_wrong, os.path.join(base_dir, 'hit1_rule_failed.xlsx'))
@@ -0,0 +1,130 @@
import openai
import os
import json
import time
import re
import pandas as pd
from tqdm import tqdm
from tenacity import retry, wait_random_exponential, stop_after_attempt
def rule_based_evaluation(item):
prediction = str(item['prediction'])
answer = str(item['answer']).strip()
boxed_matches = re.findall(r'\\boxed\{(.*?)\}', prediction)
if not boxed_matches:
return False, ""
last_boxed = boxed_matches[-1].strip()
def normalize(s):
s = re.sub(r'\$|\\[a-z]+|\s+', '', s)
s = re.sub(r'^\{|\}$', '', s)
return s.lower()
if last_boxed == answer or normalize(last_boxed) == normalize(answer):
return True, f"规则匹配:预测的 \\boxed{{{last_boxed}}} 与标准答案 '{answer}' 一致"
return False, ""
def process_one(item):
if not str(item['id']).startswith('val'):
return item
rule_match, explanation = rule_based_evaluation(item)
if rule_match:
item["is_correct"] = True
item["explanation"] = explanation
item["gpt_score"] = "规则匹配成功,跳过GPT评分"
return item
item["gpt_score"] ="" # str(e)
item["is_correct"] = False
item["explanation"] = "评分请求失败"
return item
def calculate_accuracy(jsonl_path):
correct, total, original_hit, rule_matched = 0, 0, 0, 0
single_total,single_acc=0,0
with open(jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
data = json.loads(line)
if not str(data.get('id', '')).startswith('val'):
continue
total += 1
if not "image 2" in data.get('question', '') and not "image" in data.get('A',''):
single_total+=1
if data.get('is_correct'):
correct += 1
if data.get('hit', 0) == 1:
original_hit += 1
if not "image 2" in data.get('question', '') and not "image" in data.get('A',''):
single_acc+=1
if "规则匹配" in data.get('explanation', '') and data.get('is_correct', False):
if data.get('hit', 0) == 0:
rule_matched += 1
if not "image 2" in data.get('question', '') and not "image" in data.get('A',''):
single_acc+=1
if total > 0:
print(f"\n正确率统计:")
print(f"- 总val数据量: {total}")
print(f"- 原始hit=1数量: {original_hit} ({original_hit / total * 100:.2f}%)")
print(f"- 规则匹配补正数量: {rule_matched} ({rule_matched / total * 100:.2f}%)")
print(f"- 总正确数量: {original_hit+rule_matched} ({(original_hit+rule_matched) / total * 100:.2f}%)")
else:
print("无可统计数据")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='评估回答的准确性')
parser.add_argument('--input', type=str, default='')
parser.add_argument('--output', type=str, default='./eval/vlmevalkit/outputs/Skywork-R1V3/R1V3-alpha/R1V3-alpha_MMMU_DEV_VAL_gpt4o_rule_based.jsonl')
args = parser.parse_args()
df = pd.read_excel(args.input)
data = df.to_dict('records')
with open(args.output, 'w', encoding='utf-8') as f_out:
for item in tqdm(data):
processed = process_one(item)
f_out.write(json.dumps(processed, ensure_ascii=False) + '\n')
f_out.flush()
calculate_accuracy(args.output)
print("任务完成,结果已写入文件。")
# 新增:收集分类样本
hit0_rule_correct = []
hit1_rule_wrong = []
with open(args.output, 'w', encoding='utf-8') as f_out:
for item in tqdm(data):
processed = process_one(item)
f_out.write(json.dumps(processed, ensure_ascii=False) + '\n')
f_out.flush()
if str(processed.get('id', '')).startswith('val'):
is_correct = processed.get('is_correct', False)
explanation = processed.get('explanation', '')
hit = processed.get('hit', 0)
if hit == 0 and is_correct and "规则匹配" in explanation:
hit0_rule_correct.append(processed)
elif hit == 1 and (not is_correct or "规则匹配" not in explanation):
hit1_rule_wrong.append(processed)
def save_to_excel(data_list, output_path):
if not data_list:
print(f"无数据可写入 {output_path}")
return
df_out = pd.DataFrame(data_list)
df_out.to_excel(output_path, index=False)
print(f"写入完成:{output_path}")
base_dir = os.path.dirname(args.output)
save_to_excel(hit0_rule_correct, os.path.join(base_dir, 'hit0_rule_matched.xlsx'))
save_to_excel(hit1_rule_wrong, os.path.join(base_dir, 'hit1_rule_failed.xlsx'))
+14
View File
@@ -0,0 +1,14 @@
DATA_ARGS="LogicVista"
bash ./eval/vlmevalkit/eval_shell/eval_bench.sh "$DATA_ARGS"
if [[ "$DATA_ARGS" == *"MMMU_DEV_VAL"* ]] || [[ "$DATA_ARGS" == *"MMMU_Pro_10c"* ]]; then
echo ""
echo "✅ [NOTICE] Running the rule-based check script for MMMU..."
python ./eval/vlmevalkit/eval_shell/rule_base_mmmu.py \
--input ./eval/vlmevalkit/outputs/Skywork-R1V3/R1V3-alpha/R1V3-alpha_MMMU_DEV_VAL_gpt4o_result.xlsx
elif [[ "$DATA_ARGS" == *"LogicVista"* ]]; then
echo ""
echo "✅ [NOTICE] Running the rule-based check script for LogicVista..."
python ./eval/vlmevalkit/eval_shell/rule_base_logicvista.py \
--input ./eval/vlmevalkit/outputs/Skywork-R1V3/R1V3-alpha/R1V3-alpha_LogicVista_gpt4o-mini.xlsx
fi
+41
View File
@@ -0,0 +1,41 @@
accelerate
decord; platform_machine != 'arm64'
dotenv
einops
eva-decord; platform_machine == 'arm64'
# for gemini api
google-genai
gradio
huggingface_hub
imageio
ipdb
json_repair
matplotlib
nltk
numpy
omegaconf
openai
opencv-python>=4.4.0.46
openpyxl
pandas
pillow
portalocker
protobuf
python-dotenv
qwen_vl_utils
requests
rich
sentencepiece
setuptools
sty
tabulate
tiktoken
timeout-decorator
timm
torch
torchvision
tqdm
transformers
typing_extensions
validators
xlsxwriter
+11
View File
@@ -0,0 +1,11 @@
docutils==0.18.1
modelindex
myst-parser
-e git+https://github.com/open-compass/pytorch_sphinx_theme.git#egg=pytorch_sphinx_theme
sphinx==6.1.3
sphinx-copybutton
sphinx-design
sphinx-notfound-page
sphinx-tabs
sphinxcontrib-jquery
tabulate
+493
View File
@@ -0,0 +1,493 @@
import json
import os
import subprocess
# GET the number of GPUs on the node without importing libs like torch
def get_gpu_list():
CUDA_VISIBLE_DEVICES = os.environ.get('CUDA_VISIBLE_DEVICES', '')
if CUDA_VISIBLE_DEVICES != '':
gpu_list = [int(x) for x in CUDA_VISIBLE_DEVICES.split(',')]
return gpu_list
try:
ps = subprocess.Popen(('nvidia-smi', '--list-gpus'), stdout=subprocess.PIPE)
output = subprocess.check_output(('wc', '-l'), stdin=ps.stdout)
return list(range(int(output)))
except:
return []
RANK = int(os.environ.get('RANK', 0))
WORLD_SIZE = int(os.environ.get('WORLD_SIZE', 1))
LOCAL_WORLD_SIZE = int(os.environ.get("LOCAL_WORLD_SIZE",1))
LOCAL_RANK = int(os.environ.get("LOCAL_RANK",1))
GPU_LIST = get_gpu_list()
if LOCAL_WORLD_SIZE > 1 and len(GPU_LIST):
NGPU = len(GPU_LIST)
assert NGPU >= LOCAL_WORLD_SIZE, "The number of processes should be less than or equal to the number of GPUs"
GPU_PER_PROC = NGPU // LOCAL_WORLD_SIZE
DEVICE_START_IDX = GPU_PER_PROC * LOCAL_RANK
CUDA_VISIBLE_DEVICES = [str(i) for i in GPU_LIST[DEVICE_START_IDX: DEVICE_START_IDX + GPU_PER_PROC]]
CUDA_VISIBLE_DEVICES = ','.join(CUDA_VISIBLE_DEVICES)
# Set CUDA_VISIBLE_DEVICES
os.environ['CUDA_VISIBLE_DEVICES'] = CUDA_VISIBLE_DEVICES
print(
f'RANK: {RANK}, LOCAL_RANK: {LOCAL_RANK}, WORLD_SIZE: {WORLD_SIZE},'
f'LOCAL_WORLD_SIZE: {LOCAL_WORLD_SIZE}, CUDA_VISIBLE_DEVICES: {CUDA_VISIBLE_DEVICES}'
)
from vlmeval.config import supported_VLM
from vlmeval.dataset.video_dataset_config import supported_video_datasets
from vlmeval.dataset import build_dataset
from vlmeval.inference import infer_data_job
from vlmeval.inference_video import infer_data_job_video
from vlmeval.inference_mt import infer_data_job_mt
from vlmeval.smp import *
from vlmeval.utils.result_transfer import MMMU_result_transfer, MMTBench_result_transfer
def build_model_from_config(cfg, model_name, use_vllm=False):
import vlmeval.api
import vlmeval.vlm
config = cp.deepcopy(cfg[model_name])
if use_vllm:
config['use_vllm'] = use_vllm
if 'class' not in config:
return supported_VLM[model_name](**config)
cls_name = config.pop('class')
if hasattr(vlmeval.api, cls_name):
return getattr(vlmeval.api, cls_name)(**config)
elif hasattr(vlmeval.vlm, cls_name):
return getattr(vlmeval.vlm, cls_name)(**config)
else:
raise ValueError(f'Class {cls_name} is not supported in `vlmeval.api` or `vlmeval.vlm`')
def build_dataset_from_config(cfg, dataset_name):
import vlmeval.dataset
import inspect
config = cp.deepcopy(cfg[dataset_name])
if config == {}:
return supported_video_datasets[dataset_name]()
assert 'class' in config
cls_name = config.pop('class')
if hasattr(vlmeval.dataset, cls_name):
cls = getattr(vlmeval.dataset, cls_name)
sig = inspect.signature(cls.__init__)
valid_params = {k: v for k, v in config.items() if k in sig.parameters}
if cls.MODALITY == 'VIDEO':
if valid_params.get('fps', 0) > 0 and valid_params.get('nframe', 0) > 0:
raise ValueError('fps and nframe should not be set at the same time')
if valid_params.get('fps', 0) <= 0 and valid_params.get('nframe', 0) <= 0:
raise ValueError('fps and nframe should be set at least one valid value')
return cls(**valid_params)
else:
raise ValueError(f'Class {cls_name} is not supported in `vlmeval.dataset`')
def parse_args():
help_msg = """\
You can launch the evaluation by setting either --data and --model or --config.
--data and --model:
Each Arg should be a list of strings, specifying the names of datasets and models.
To find all supported model names, please refer to the `vlmeval/config.py` of check the output of the command \
`vlmutil mlist all` in the terminal (you should first have vlmeval installed).
To find all supported dataset names, please refer to the `vlmeval/dataset/__init__.py` file. The python script \
to print all supported dataset names is as follows:
```python
from vlmeval.dataset import SUPPORTED_DATASETS
print(SUPPORTED_DATASETS)
```
or you can check the output of the command `vlmutil dlist all` in the terminal.
To find all supported video dataset default settings, please refer to the \
`vlmeval/dataset/video_dataset_config.py` file.
--config:
Launch the evaluation by specifying the path to the config json file. Sample Json Content:
```json
{
"model": {
"GPT4o_20240806_T00_HIGH": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 0,
"img_detail": "high"
},
"GPT4o_20240806_T10_Low": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 1.0,
"img_detail": "low"
},
"GPT4o_20241120": {}
},
"data": {
"MME-RealWorld-Lite": {
"class": "MMERealWorld",
"dataset": "MME-RealWorld-Lite"
},
"MMBench_DEV_EN_V11": {
"class": "ImageMCQDataset",
"dataset": "MMBench_DEV_EN_V11"
},
"MMBench_Video_8frame_nopack": {},
"Video-MME_16frame_subs": {
"class": "VideoMME",
"dataset": "Video-MME",
"nframe": 16,
"use_subtitle": true,
}
}
}
```
Currently, only `model` and `data` are supported fields. The content of each field is a dictionary.
For `model`, the key is the name of the model, and the value is a dictionary containing the following keys:
- `class`: The class name of the model, which should be a class in `vlmeval.vlm` or `vlmeval.api`.
- Other keys are specific to the model, please refer to the corresponding class.
- Tip: The defined model in the `supported_VLM` of `vlmeval/config.py` can be used as a shortcut.
For `data`, the key is the name of the dataset (should be the same as the `dataset` field in most cases, \
except for video datasets), and the value is a dictionary containing the following keys:
- `class`: The class name of the dataset, which should be a class in `vlmeval.dataset`.
- `dataset`: The name of the dataset, which should be a string that is accepted by the `dataset` argument of the \
corresponding class.
- Other keys are specific to the dataset, please refer to the corresponding class.
- Tip: The defined dataset in the `supported_video_datasets` of `vlmeval/dataset/video_dataset_config.py` \
can be used as a shortcut.
The keys in the `model` and `data` fields will be used for naming the prediction files and evaluation results.
When launching with `--config`, args for API VLMs, such as `--retry`, `--verbose`, will be ignored.
"""
parser = argparse.ArgumentParser(description=help_msg, formatter_class=argparse.RawTextHelpFormatter)
# Essential Args, Setting the Names of Datasets and Models
parser.add_argument('--data', type=str, nargs='+', help='Names of Datasets')
parser.add_argument('--model', type=str, nargs='+', help='Names of Models')
parser.add_argument('--config', type=str, help='Path to the Config Json File')
# Work Dir
parser.add_argument('--work-dir', type=str, default='./outputs', help='select the output directory')
# Infer + Eval or Infer Only
parser.add_argument('--mode', type=str, default='all', choices=['all', 'infer'])
# API Kwargs, Apply to API VLMs and Judge API LLMs
parser.add_argument('--api-nproc', type=int, default=4, help='Parallel API calling')
parser.add_argument('--retry', type=int, default=None, help='retry numbers for API VLMs')
parser.add_argument('--judge-args', type=str, default=None, help='Judge arguments in JSON format')
# Explicitly Set the Judge Model
parser.add_argument('--judge', type=str, default=None)
# Logging Utils
parser.add_argument('--verbose', action='store_true')
# Configuration for Resume
# Ignore: will not rerun failed VLM inference
parser.add_argument('--ignore', action='store_true', help='Ignore failed indices. ')
# Reuse: will reuse the existing prediction files
parser.add_argument('--reuse', action='store_true')
# Reuse-aux: if set, when reuse is True, will also reuse the auxiliary evaluation files
parser.add_argument('--reuse-aux', type=bool, default=True, help='reuse auxiliary evaluation files')
parser.add_argument(
'--use-vllm', action='store_true', help='use vllm to generate, the flag is only supported in Llama4 for now')
args = parser.parse_args()
return args
def main():
logger = get_logger('RUN')
args = parse_args()
use_config, cfg = False, None
if args.config is not None:
assert args.data is None and args.model is None, '--data and --model should not be set when using --config'
use_config, cfg = True, load(args.config)
args.model = list(cfg['model'].keys())
args.data = list(cfg['data'].keys())
else:
assert len(args.data), '--data should be a list of data files'
if RANK == 0:
if not args.reuse:
logger.warning('--reuse is not set, will not reuse previous (before one day) temporary files')
else:
logger.warning('--reuse is set, will reuse the latest prediction & temporary pickle files')
if 'MMEVAL_ROOT' in os.environ:
args.work_dir = os.environ['MMEVAL_ROOT']
if not use_config:
for k, v in supported_VLM.items():
if hasattr(v, 'keywords') and 'retry' in v.keywords and args.retry is not None:
v.keywords['retry'] = args.retry
supported_VLM[k] = v
if hasattr(v, 'keywords') and 'verbose' in v.keywords and args.verbose is not None:
v.keywords['verbose'] = args.verbose
supported_VLM[k] = v
if WORLD_SIZE > 1:
import torch.distributed as dist
dist.init_process_group(
backend='nccl',
timeout=datetime.timedelta(seconds=int(os.environ.get('DIST_TIMEOUT', 3600)))
)
for _, model_name in enumerate(args.model):
model = None
date, commit_id = timestr('day'), githash(digits=8)
eval_id = f"T{date}_G{commit_id}"
pred_root = osp.join(args.work_dir, model_name, eval_id)
pred_root_meta = osp.join(args.work_dir, model_name)
os.makedirs(pred_root_meta, exist_ok=True)
prev_pred_roots = ls(osp.join(args.work_dir, model_name), mode='dir')
if len(prev_pred_roots) and args.reuse:
prev_pred_roots.sort()
if not osp.exists(pred_root):
os.makedirs(pred_root, exist_ok=True)
if use_config:
model = build_model_from_config(cfg['model'], model_name, args.use_vllm)
for _, dataset_name in enumerate(args.data):
if WORLD_SIZE > 1:
dist.barrier()
try:
result_file_base = f'{model_name}_{dataset_name}.xlsx'
if use_config:
if WORLD_SIZE > 1:
if RANK == 0:
dataset = build_dataset_from_config(cfg['data'], dataset_name)
dist.barrier()
dataset = build_dataset_from_config(cfg['data'], dataset_name)
if dataset is None:
logger.error(f'Dataset {dataset_name} is not valid, will be skipped. ')
continue
else:
dataset_kwargs = {}
if dataset_name in ['MMLongBench_DOC', 'DUDE', 'DUDE_MINI', 'SLIDEVQA', 'SLIDEVQA_MINI']:
dataset_kwargs['model'] = model_name
# If distributed, first build the dataset on the main process for doing preparation works
if WORLD_SIZE > 1:
if RANK == 0:
dataset = build_dataset(dataset_name, **dataset_kwargs)
dist.barrier()
dataset = build_dataset(dataset_name, **dataset_kwargs)
if dataset is None:
logger.error(f'Dataset {dataset_name} is not valid, will be skipped. ')
continue
# Handling Multi-Turn Dataset
if dataset.TYPE == 'MT':
result_file_base = result_file_base.replace('.xlsx', '.tsv')
result_file = osp.join(pred_root, result_file_base)
# Reuse the previous prediction file if exists
if RANK == 0 and len(prev_pred_roots):
prev_result_files = []
prev_pkl_file_list = []
for root in prev_pred_roots[::-1]:
if osp.exists(osp.join(root, result_file_base)):
if args.reuse_aux:
prev_result_files = fetch_aux_files(osp.join(root, result_file_base))
else:
prev_result_files = [osp.join(root, result_file_base)]
break
elif commit_id in root and len(ls(root)) and root != pred_root:
temp_files = ls(root, match=[dataset_name, '.pkl'])
if len(temp_files):
prev_pkl_file_list.extend(temp_files)
break
if not args.reuse:
prev_result_files = []
prev_pkl_file_list = []
if len(prev_result_files):
for prev_result_file in prev_result_files:
src = prev_result_file
tgt = osp.join(pred_root, osp.basename(src))
if not osp.exists(tgt):
shutil.copy(src, tgt)
logger.info(f'--reuse is set, will reuse the prediction file {src}.')
else:
logger.warning(f'File already exists: {tgt}')
elif len(prev_pkl_file_list):
for fname in prev_pkl_file_list:
target_path = osp.join(pred_root, osp.basename(fname))
if not osp.exists(target_path):
shutil.copy(fname, target_path)
logger.info(f'--reuse is set, will reuse the prediction pickle file {fname}.')
else:
logger.warning(f'File already exists: {target_path}')
if WORLD_SIZE > 1:
dist.barrier()
if model is None:
model = model_name # which is only a name
# Perform the Inference
if dataset.MODALITY == 'VIDEO':
model = infer_data_job_video(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
result_file_name=result_file_base,
verbose=args.verbose,
api_nproc=args.api_nproc,
use_vllm=args.use_vllm)
elif dataset.TYPE == 'MT':
model = infer_data_job_mt(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
verbose=args.verbose,
api_nproc=args.api_nproc,
ignore_failed=args.ignore,
use_vllm=args.use_vllm)
else:
model = infer_data_job(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
verbose=args.verbose,
api_nproc=args.api_nproc,
ignore_failed=args.ignore,
use_vllm=args.use_vllm)
# Set the judge kwargs first before evaluation or dumping
judge_kwargs = {
'nproc': args.api_nproc,
'verbose': args.verbose,
'retry': args.retry if args.retry is not None else 3,
**(json.loads(args.judge_args) if args.judge_args else {}),
}
if args.retry is not None:
judge_kwargs['retry'] = args.retry
if args.judge is not None:
judge_kwargs['model'] = args.judge
else:
print(dataset_name)
if dataset.TYPE in ['MCQ', 'Y/N', 'MCQ_MMMU_Pro'] or listinstr(
['moviechat1k', 'mme-reasoning'], dataset_name.lower()
):
if listinstr(['WeMath'], dataset_name):
judge_kwargs['model'] = 'gpt-4o-mini'
elif listinstr(['VisuLogic'], dataset_name):
judge_kwargs['model'] = 'exact_matching'
else:
judge_kwargs['model'] = 'chatgpt-0125'
elif listinstr(['MMVet', 'LLaVABench', 'MMBench_Video', "VisualPuzzles"], dataset_name):
judge_kwargs['model'] = 'gpt-4-turbo'
elif listinstr(['VGRPBench'], dataset_name):
judge_kwargs['model'] = 'gpt-4o'
elif listinstr(['MathVista', 'MathVerse', 'MathVision', 'DynaMath', 'VL-RewardBench', 'LogicVista', 'MOAT', 'OCR_Reasoning', "MMEReasoning"], dataset_name): # noqa: E501
judge_kwargs['model'] = 'gpt-4o-mini'
elif listinstr(['MMLongBench', 'MMDU', 'DUDE', 'SLIDEVQA', 'MIA-Bench', 'WildVision', 'MMAlignBench', 'MM-IFEval'], dataset_name): # noqa: E501
judge_kwargs['model'] = 'gpt-4o'
elif listinstr(['VDC'], dataset_name):
judge_kwargs['model'] = 'llama31-8b'
elif listinstr(['VideoMMLU_QA', 'VideoMMLU_CAP'], dataset_name):
judge_kwargs['model'] = 'qwen-72b'
if RANK == 0:
logger.info(judge_kwargs)
if WORLD_SIZE > 1:
dist.barrier()
# Only RANK 0 handles the evaluation part
if RANK == 0:
# Prepare Submission Files for MMMU_TEST AND MMT-Bench_ALL
if dataset_name in ['MMMU_TEST']:
result_json = MMMU_result_transfer(result_file)
logger.info(f'Transfer MMMU_TEST result to json for official evaluation, '
f'json file saved in {result_json}')
continue
elif 'MMT-Bench_ALL' in dataset_name:
submission_file = MMTBench_result_transfer(result_file, **judge_kwargs)
logger.info(f'Extract options from prediction of MMT-Bench FULL split for official evaluation '
f'(https://eval.ai/web/challenges/challenge-page/2328/overview), '
f'submission file saved in {submission_file}')
continue
# Skip the evaluation part if only infer
if args.mode == 'infer':
continue
# Skip the evaluation part if the dataset evaluation is not supported or annotations are missing
if 'MLLMGuard_DS' in dataset_name:
logger.info('The evaluation of MLLMGuard_DS is not supported yet. ')
continue
elif 'AesBench_TEST' == dataset_name:
logger.info(f'The results are saved in {result_file}. '
f'Please send it to the AesBench Team via huangyipo@hotmail.com.')
continue
elif dataset_name in ['DocVQA_TEST', 'InfoVQA_TEST', 'Q-Bench1_TEST', 'A-Bench_TEST']:
logger.info(f'{dataset_name} is a test split without ground-truth. '
'Thus only the inference part is supported for those datasets. ')
continue
elif dataset_name in [
'MMBench_TEST_CN', 'MMBench_TEST_EN', 'MMBench', 'MMBench_CN',
'MMBench_TEST_CN_V11', 'MMBench_TEST_EN_V11', 'MMBench_V11', 'MMBench_CN_V11'
] and not MMBenchOfficialServer(dataset_name):
logger.error(
f'Can not evaluate {dataset_name} on non-official servers, will skip the evaluation.')
continue
# Setup the proxy for the evaluation
eval_proxy = os.environ.get('EVAL_PROXY', None)
old_proxy = os.environ.get('HTTP_PROXY', '')
if eval_proxy is not None:
proxy_set(eval_proxy)
# Perform the Evaluation
eval_results = dataset.evaluate(result_file, **judge_kwargs)
# Display Evaluation Results in Terminal
if eval_results is not None:
assert isinstance(eval_results, dict) or isinstance(eval_results, pd.DataFrame)
logger.info(f'The evaluation of model {model_name} x dataset {dataset_name} has finished! ')
logger.info('Evaluation Results:')
if isinstance(eval_results, dict):
logger.info('\n' + json.dumps(eval_results, indent=4))
elif isinstance(eval_results, pd.DataFrame):
if len(eval_results) < len(eval_results.columns):
eval_results = eval_results.T
logger.info('\n' + tabulate(eval_results))
# Restore the proxy
if eval_proxy is not None:
proxy_set(old_proxy)
# Create the symbolic links for the prediction files
files = os.listdir(pred_root)
files = [x for x in files if (f'{model_name}_{dataset_name}' in x or "status.json" in x)]
for f in files:
cwd = os.getcwd()
file_addr = osp.join(cwd, pred_root, f)
link_addr = osp.join(cwd, pred_root_meta, f)
if osp.exists(link_addr) or osp.islink(link_addr):
os.remove(link_addr)
os.symlink(file_addr, link_addr)
except Exception as e:
logger.exception(f'Model {model_name} x Dataset {dataset_name} combination failed: {e}, '
'skipping this combination.')
continue
if WORLD_SIZE > 1:
dist.destroy_process_group()
if __name__ == '__main__':
load_env()
main()
+557
View File
@@ -0,0 +1,557 @@
import json
import os
import subprocess
# GET the number of GPUs on the node without importing libs like torch
def get_gpu_list():
CUDA_VISIBLE_DEVICES = os.environ.get('CUDA_VISIBLE_DEVICES', '')
if CUDA_VISIBLE_DEVICES != '':
gpu_list = [int(x) for x in CUDA_VISIBLE_DEVICES.split(',')]
return gpu_list
try:
ps = subprocess.Popen(('nvidia-smi', '--list-gpus'), stdout=subprocess.PIPE)
output = subprocess.check_output(('wc', '-l'), stdin=ps.stdout)
return list(range(int(output)))
except:
return []
RANK = int(os.environ.get('RANK', 0))
WORLD_SIZE = int(os.environ.get('WORLD_SIZE', 1))
LOCAL_WORLD_SIZE = int(os.environ.get("LOCAL_WORLD_SIZE",1))
LOCAL_RANK = int(os.environ.get("LOCAL_RANK",1))
GPU_LIST = get_gpu_list()
if LOCAL_WORLD_SIZE > 1 and len(GPU_LIST):
NGPU = len(GPU_LIST)
assert NGPU >= LOCAL_WORLD_SIZE, "The number of processes should be less than or equal to the number of GPUs"
GPU_PER_PROC = NGPU // LOCAL_WORLD_SIZE
DEVICE_START_IDX = GPU_PER_PROC * LOCAL_RANK
CUDA_VISIBLE_DEVICES = [str(i) for i in GPU_LIST[DEVICE_START_IDX: DEVICE_START_IDX + GPU_PER_PROC]]
CUDA_VISIBLE_DEVICES = ','.join(CUDA_VISIBLE_DEVICES)
# Set CUDA_VISIBLE_DEVICES
os.environ['CUDA_VISIBLE_DEVICES'] = CUDA_VISIBLE_DEVICES
print(
f'RANK: {RANK}, LOCAL_RANK: {LOCAL_RANK}, WORLD_SIZE: {WORLD_SIZE},'
f'LOCAL_WORLD_SIZE: {LOCAL_WORLD_SIZE}, CUDA_VISIBLE_DEVICES: {CUDA_VISIBLE_DEVICES}'
)
from vlmeval.config import supported_VLM
from vlmeval.dataset.video_dataset_config import supported_video_datasets
from vlmeval.dataset import build_dataset
from vlmeval.inference import infer_data_job
from vlmeval.inference_video import infer_data_job_video
from vlmeval.inference_mt import infer_data_job_mt
from vlmeval.smp import *
from vlmeval.utils.result_transfer import MMMU_result_transfer, MMTBench_result_transfer
def build_model_from_config(cfg, model_name, use_vllm=False):
import vlmeval.api
import vlmeval.vlm
config = cp.deepcopy(cfg[model_name])
if use_vllm:
config['use_vllm'] = use_vllm
if 'class' not in config:
return supported_VLM[model_name](**config)
cls_name = config.pop('class')
if hasattr(vlmeval.api, cls_name):
return getattr(vlmeval.api, cls_name)(**config)
elif hasattr(vlmeval.vlm, cls_name):
return getattr(vlmeval.vlm, cls_name)(**config)
else:
raise ValueError(f'Class {cls_name} is not supported in `vlmeval.api` or `vlmeval.vlm`')
def build_dataset_from_config(cfg, dataset_name):
import vlmeval.dataset
import inspect
config = cp.deepcopy(cfg[dataset_name])
if config == {}:
return supported_video_datasets[dataset_name]()
assert 'class' in config
cls_name = config.pop('class')
if hasattr(vlmeval.dataset, cls_name):
cls = getattr(vlmeval.dataset, cls_name)
sig = inspect.signature(cls.__init__)
valid_params = {k: v for k, v in config.items() if k in sig.parameters}
if cls.MODALITY == 'VIDEO':
if valid_params.get('fps', 0) > 0 and valid_params.get('nframe', 0) > 0:
raise ValueError('fps and nframe should not be set at the same time')
if valid_params.get('fps', 0) <= 0 and valid_params.get('nframe', 0) <= 0:
raise ValueError('fps and nframe should be set at least one valid value')
return cls(**valid_params)
else:
raise ValueError(f'Class {cls_name} is not supported in `vlmeval.dataset`')
def parse_args():
help_msg = """\
You can launch the evaluation by setting either --data and --model or --config.
--data and --model:
Each Arg should be a list of strings, specifying the names of datasets and models.
To find all supported model names, please refer to the `vlmeval/config.py` of check the output of the command \
`vlmutil mlist all` in the terminal (you should first have vlmeval installed).
To find all supported dataset names, please refer to the `vlmeval/dataset/__init__.py` file. The python script \
to print all supported dataset names is as follows:
```python
from vlmeval.dataset import SUPPORTED_DATASETS
print(SUPPORTED_DATASETS)
```
or you can check the output of the command `vlmutil dlist all` in the terminal.
To find all supported video dataset default settings, please refer to the \
`vlmeval/dataset/video_dataset_config.py` file.
--config:
Launch the evaluation by specifying the path to the config json file. Sample Json Content:
```json
{
"model": {
"GPT4o_20240806_T00_HIGH": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 0,
"img_detail": "high"
},
"GPT4o_20240806_T10_Low": {
"class": "GPT4V",
"model": "gpt-4o-2024-08-06",
"temperature": 1.0,
"img_detail": "low"
},
"GPT4o_20241120": {}
},
"data": {
"MME-RealWorld-Lite": {
"class": "MMERealWorld",
"dataset": "MME-RealWorld-Lite"
},
"MMBench_DEV_EN_V11": {
"class": "ImageMCQDataset",
"dataset": "MMBench_DEV_EN_V11"
},
"MMBench_Video_8frame_nopack": {},
"Video-MME_16frame_subs": {
"class": "VideoMME",
"dataset": "Video-MME",
"nframe": 16,
"use_subtitle": true,
}
}
}
```
Currently, only `model` and `data` are supported fields. The content of each field is a dictionary.
For `model`, the key is the name of the model, and the value is a dictionary containing the following keys:
- `class`: The class name of the model, which should be a class in `vlmeval.vlm` or `vlmeval.api`.
- Other keys are specific to the model, please refer to the corresponding class.
- Tip: The defined model in the `supported_VLM` of `vlmeval/config.py` can be used as a shortcut.
For `data`, the key is the name of the dataset (should be the same as the `dataset` field in most cases, \
except for video datasets), and the value is a dictionary containing the following keys:
- `class`: The class name of the dataset, which should be a class in `vlmeval.dataset`.
- `dataset`: The name of the dataset, which should be a string that is accepted by the `dataset` argument of the \
corresponding class.
- Other keys are specific to the dataset, please refer to the corresponding class.
- Tip: The defined dataset in the `supported_video_datasets` of `vlmeval/dataset/video_dataset_config.py` \
can be used as a shortcut.
The keys in the `model` and `data` fields will be used for naming the prediction files and evaluation results.
When launching with `--config`, args for API VLMs, such as `--retry`, `--verbose`, will be ignored.
"""
parser = argparse.ArgumentParser(description=help_msg, formatter_class=argparse.RawTextHelpFormatter)
# Essential Args, Setting the Names of Datasets and Models
parser.add_argument('--data', type=str, nargs='+', help='Names of Datasets')
parser.add_argument('--model', type=str, nargs='+', help='Names of Models')
parser.add_argument('--config', type=str, help='Path to the Config Json File')
# Work Dir
parser.add_argument('--work-dir', type=str, default='./outputs', help='select the output directory')
# Infer + Eval or Infer Only
parser.add_argument('--mode', type=str, default='all', choices=['all', 'infer'])
# API Kwargs, Apply to API VLMs and Judge API LLMs
parser.add_argument('--api-nproc', type=int, default=4, help='Parallel API calling')
parser.add_argument('--retry', type=int, default=None, help='retry numbers for API VLMs')
parser.add_argument('--judge-args', type=str, default=None, help='Judge arguments in JSON format')
# Explicitly Set the Judge Model
parser.add_argument('--judge', type=str, default=None)
# Logging Utils
parser.add_argument('--verbose', action='store_true')
# Configuration for Resume
# Ignore: will not rerun failed VLM inference
parser.add_argument('--ignore', action='store_true', help='Ignore failed indices. ')
# Reuse: will reuse the existing prediction files
parser.add_argument('--reuse', action='store_true')
# Reuse-aux: if set, when reuse is True, will also reuse the auxiliary evaluation files
parser.add_argument('--reuse-aux', type=bool, default=True, help='reuse auxiliary evaluation files')
parser.add_argument(
'--use-vllm', action='store_true', help='use vllm to generate, the flag is only supported in Llama4 for now')
args = parser.parse_args()
return args
def main():
import os
logger = get_logger('RUN')
args = parse_args()
use_config, cfg = False, None
if args.config is not None:
assert args.data is None and args.model is None, '--data and --model should not be set when using --config'
use_config, cfg = True, load(args.config)
args.model = list(cfg['model'].keys())
args.data = list(cfg['data'].keys())
else:
assert len(args.data), '--data should be a list of data files'
if RANK == 0:
if not args.reuse:
logger.warning('--reuse is not set, will not reuse previous (before one day) temporary files')
else:
logger.warning('--reuse is set, will reuse the latest prediction & temporary pickle files')
# if 'MMEVAL_ROOT' in os.environ:
# args.work_dir = os.environ['MMEVAL_ROOT']
print('-------------------')
if not use_config:
for k, v in supported_VLM.items():
if hasattr(v, 'keywords') and 'retry' in v.keywords and args.retry is not None:
v.keywords['retry'] = args.retry
supported_VLM[k] = v
if hasattr(v, 'keywords') and 'verbose' in v.keywords and args.verbose is not None:
v.keywords['verbose'] = args.verbose
supported_VLM[k] = v
print('-------------------')
if WORLD_SIZE > 1:
import torch.distributed as dist
dist.init_process_group(
backend='nccl',
timeout=datetime.timedelta(seconds=int(os.environ.get('DIST_TIMEOUT', 3600)))
)
for _, model_name in enumerate(args.model):
print('-------------------')
model = None
date, commit_id = timestr('day'), githash(digits=8)
eval_id = f"T{date}_G{commit_id}"
pred_root = osp.join(args.work_dir, model_name, eval_id)
pred_root_meta = osp.join(args.work_dir, model_name)
os.makedirs(pred_root_meta, exist_ok=True)
print('-------------------')
prev_pred_roots = ls(osp.join(args.work_dir, model_name), mode='dir')
if len(prev_pred_roots) and args.reuse:
prev_pred_roots.sort()
if not osp.exists(pred_root):
os.makedirs(pred_root, exist_ok=True)
if use_config:
model = build_model_from_config(cfg['model'], model_name, args.use_vllm)
print('-------------------')
for _, dataset_name in enumerate(args.data):
print('-------------------dsd')
if WORLD_SIZE > 1:
dist.barrier()
try:
result_file_base = f'{model_name}_{dataset_name}.xlsx'
if use_config:
if WORLD_SIZE > 1:
if RANK == 0:
dataset = build_dataset_from_config(cfg['data'], dataset_name)
dist.barrier()
dataset = build_dataset_from_config(cfg['data'], dataset_name)
if dataset is None:
logger.error(f'Dataset {dataset_name} is not valid, will be skipped. ')
continue
else:
dataset_kwargs = {}
if dataset_name in ['MMLongBench_DOC', 'DUDE', 'DUDE_MINI', 'SLIDEVQA', 'SLIDEVQA_MINI']:
dataset_kwargs['model'] = model_name
# If distributed, first build the dataset on the main process for doing preparation works
if WORLD_SIZE > 1:
if RANK == 0:
dataset = build_dataset(dataset_name, **dataset_kwargs)
dist.barrier()
dataset = build_dataset(dataset_name, **dataset_kwargs)
if dataset is None:
logger.error(f'Dataset {dataset_name} is not valid, will be skipped. ')
continue
print(dataset)
print('----------------dxsdsds---')
# Handling Multi-Turn Dataset
if dataset.TYPE == 'MT':
result_file_base = result_file_base.replace('.xlsx', '.tsv')
result_file = osp.join(pred_root, result_file_base)
# Reuse the previous prediction file if exists
if RANK == 0 and len(prev_pred_roots):
prev_result_files = []
prev_pkl_file_list = []
for root in prev_pred_roots[::-1]:
if osp.exists(osp.join(root, result_file_base)):
if args.reuse_aux:
prev_result_files = fetch_aux_files(osp.join(root, result_file_base))
else:
prev_result_files = [osp.join(root, result_file_base)]
break
elif commit_id in root and len(ls(root)) and root != pred_root:
temp_files = ls(root, match=[dataset_name, '.pkl'])
if len(temp_files):
prev_pkl_file_list.extend(temp_files)
break
if not args.reuse:
prev_result_files = []
prev_pkl_file_list = []
if len(prev_result_files):
for prev_result_file in prev_result_files:
src = prev_result_file
tgt = osp.join(pred_root, osp.basename(src))
if not osp.exists(tgt):
shutil.copy(src, tgt)
logger.info(f'--reuse is set, will reuse the prediction file {src}.')
else:
logger.warning(f'File already exists: {tgt}')
elif len(prev_pkl_file_list):
for fname in prev_pkl_file_list:
target_path = osp.join(pred_root, osp.basename(fname))
if not osp.exists(target_path):
shutil.copy(fname, target_path)
logger.info(f'--reuse is set, will reuse the prediction pickle file {fname}.')
else:
logger.warning(f'File already exists: {target_path}')
if WORLD_SIZE > 1:
dist.barrier()
if model is None:
model = model_name # which is only a name
# Perform the Inference
if dataset.MODALITY == 'VIDEO':
model = infer_data_job_video(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
result_file_name=result_file_base,
verbose=args.verbose,
api_nproc=args.api_nproc,
use_vllm=args.use_vllm)
elif dataset.TYPE == 'MT':
model = infer_data_job_mt(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
verbose=args.verbose,
api_nproc=args.api_nproc,
ignore_failed=args.ignore,
use_vllm=args.use_vllm)
else:
model = infer_data_job(
model,
work_dir=pred_root,
model_name=model_name,
dataset=dataset,
verbose=args.verbose,
api_nproc=args.api_nproc,
ignore_failed=args.ignore,
use_vllm=args.use_vllm)
# Set the judge kwargs first before evaluation or dumping
judge_kwargs = {
'nproc': args.api_nproc,
'verbose': args.verbose,
'retry': args.retry if args.retry is not None else 3,
**(json.loads(args.judge_args) if args.judge_args else {}),
}
if args.retry is not None:
judge_kwargs['retry'] = args.retry
if args.judge is not None:
judge_kwargs['model'] = args.judge
else:
print(dataset_name)
if dataset.TYPE in ['MCQ', 'Y/N', 'MCQ_MMMU_Pro'] or listinstr(
['moviechat1k'], dataset_name.lower()
):
if listinstr(['WeMath'], dataset_name):
judge_kwargs['model'] = 'gpt-4o-mini'
elif listinstr(['VisuLogic'], dataset_name):
judge_kwargs['model'] = 'exact_matching'
else:
judge_kwargs['model'] = 'chatgpt-0125'
elif listinstr(['MMVet', 'LLaVABench', 'MMBench_Video'], dataset_name):
judge_kwargs['model'] = 'gpt-4-turbo'
elif listinstr(['VGRPBench'], dataset_name):
judge_kwargs['model'] = 'gpt-4o'
elif listinstr(['MathVista', 'MathVerse', 'MathVision', 'DynaMath', 'VL-RewardBench', 'LogicVista', 'MOAT', 'OCR_Reasoning'], dataset_name): # noqa: E501
judge_kwargs['model'] = 'gpt-4o-mini'
elif listinstr(['MMLongBench', 'MMDU', 'DUDE', 'SLIDEVQA', 'MIA-Bench', 'WildVision', 'MMAlignBench', 'MM-IFEval'], dataset_name): # noqa: E501
judge_kwargs['model'] = 'gpt-4o'
elif listinstr(['VDC'], dataset_name):
judge_kwargs['model'] = 'llama31-8b'
elif listinstr(['VideoMMLU_QA', 'VideoMMLU_CAP'], dataset_name):
judge_kwargs['model'] = 'qwen-72b'
if RANK == 0:
logger.info(judge_kwargs)
if WORLD_SIZE > 1:
dist.barrier()
# Only RANK 0 handles the evaluation part
if RANK == 0:
import pandas as pd
data = pd.read_excel(result_file)
items = []
items_1 = []
count = 0
for i in range(len(data['id'])):
prediction = data['prediction'][i]
answer = 'boxed{' + data['answer'][i] + '}'
if(answer in prediction):
count = count + 1
item = {
"question": data['question'][i],
"prediction": data['prediction'][i],
"answer": data['answer'][i],
"category": data['category'][i],
"A": data['A'][i],
"B": data['B'][i],
"C": data['C'][i],
"D": data['D'][i],
"right": True
}
items_1.append(item)
else:
item = {
"question": data['question'][i],
"prediction": data['prediction'][i],
"answer": data['answer'][i],
"category": data['category'][i],
"A": data['A'][i],
"B": data['B'][i],
"C": data['C'][i],
"D": data['D'][i],
"right": False
}
items.append(item)
count_Op = 0
count_WA = 0
count_Th = 0
count_MP = 0
count_Me = 0
count_El = 0
count_Op_right = 0
count_WA_right = 0
count_Th_right = 0
count_MP_right = 0
count_Me_right = 0
count_El_right = 0
import openai
import os
GPTAppKey = 'xxx'
app_key = os.environ.get('GPTAppKey', GPTAppKey)
if app_key == '':
print("未设置环境变量 GPTAppKey")
exit(1)
ai = openai.OpenAI(
base_url="xxx",
api_key=app_key,
)
model_name = 'deepseek-chat'
def format_prompt(item):
base_prompt = """判断AI回答是否正确,只需要回答,yes or no""" # 和原来的base_prompt保持一致,可保留不变
choices_parts = [f"{opt}. {item[opt]}" for opt in ['A', 'B', 'C', 'D'] if opt in item and pd.notna(item[opt])]
choices_str = "\n".join(choices_parts) if choices_parts else "无选项"
prompt = (
f"#问题#\n{item['question']}\n\n"
f"#选项#\n{choices_str}\n\n"
f"#AI回答#\n{item['prediction']}\n\n"
f"#标准答案#\n{item['answer']}\n\n"
f"{base_prompt}"
)
return prompt
def get_ans(prompt):
messages = [{"role": "user", "content": prompt}]
response = ai.chat.completions.create(
model=model_name,
messages=messages,
stream=False,
temperature=0.1,
presence_penalty=0.3,
top_p=0.7,
max_tokens=4000
)
return response.choices[0].message.content
response_LLM = []
length = len(items)
for i in tqdm(range(length)):
prompt = format_prompt(items[i])
ans = get_ans(prompt)
response_LLM.append(ans)
if(ans!='no'):
items[i]["right"] = True
data = items_1 + items
for i in range(len(data)):
item = data[i]
if(item['category']=='Optics'):
count_Op = count_Op + 1
if(item['right'] == True):
count_Op_right = count_Op_right + 1
if(item['category']=='Thermodynamics'):
count_Th = count_Th + 1
if(item['right'] == True):
count_Th_right = count_Th_right + 1
if(item['category']=='Waves/Acoustics'):
count_WA = count_WA + 1
if(item['right'] == True):
count_WA_right = count_WA_right + 1
if(item['category']=='Modern Physics'):
count_MP = count_MP + 1
if(item['right'] == True):
count_MP_right = count_MP_right + 1
if(item['category']=='Mechanics'):
count_Me = count_Me + 1
if(item['right'] == True):
count_Me_right = count_Me_right + 1
if(item['category']=='Electromagnetism'):
count_El = count_El + 1
if(item['right'] == True):
count_El_right = count_El_right + 1
print('Optics Accuracy: ',count_Op_right/count_Op)
print('Thermodynamics Accuracy: ',count_Th_right/count_Th)
print('Waves/Acoustics Accuracy: ',count_WA_right/count_WA)
print('Modern Physics Accuracy: ',count_MP_right/count_MP)
print('Mechanics Accuracy: ',count_Me_right/count_Me)
print('Electromagnetism Accuracy: ',count_El_right/count_El)
print('Total Accuracy: ',(count_Op_right+count_Th_right+count_WA_right+count_MP_right+count_Me_right+count_El_right)/(count_Op+count_Th+count_WA+count_MP+count_Me+count_El))
except Exception as e:
logger.exception(f'Model {model_name} x Dataset {dataset_name} combination failed: {e}, '
'skipping this combination.')
continue
if WORLD_SIZE > 1:
dist.destroy_process_group()
if __name__ == '__main__':
load_env()
main()
+261
View File
@@ -0,0 +1,261 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os, cv2\n",
"import string\n",
"import os.path as osp\n",
"import numpy as np\n",
"from collections import defaultdict\n",
"from vlmeval.smp import ls, load, dump, download_file, encode_image_file_to_base64, md5, mrlines\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import multiprocessing as mp\n",
"from PIL import Image, ImageFont, ImageDraw\n",
"\n",
"font_URL = 'http://opencompass.openxlab.space/utils/Fonts/timesb.ttf'\n",
"font_file = 'timesb.ttf'\n",
"if not osp.exists(font_file):\n",
" download_file(font_URL)\n",
" \n",
"test_split_URL = 'https://s3-us-east-2.amazonaws.com/prior-datasets/ai2d_test_ids.csv'\n",
"test_split_file = 'ai2d_test_ids.csv'\n",
"if not osp.exists(test_split_file):\n",
" download_file(test_split_URL)\n",
" \n",
"test_ids = set(mrlines(test_split_file))\n",
" \n",
"def proper_font_size(font_file, wh, text, ratio=1):\n",
" font_size = 2\n",
" while True:\n",
" font = ImageFont.truetype(font_file, font_size)\n",
" real_box = font.getbbox(text)\n",
" real_wh = (real_box[2] - real_box[0], real_box[3] - real_box[1])\n",
" if real_wh[0] > wh[0] * ratio or real_wh[1] > wh[1] * ratio:\n",
" break\n",
" font_size += 1\n",
" return font_size\n",
"\n",
"def cover_image(ann_path):\n",
" data = load(ann_path)\n",
" texts = list(data['text'].values())\n",
" raw_img = ann_path.replace('annotations', 'images').replace('.json', '')\n",
" tgt_img = raw_img.replace('images', 'images_abc')\n",
" img = Image.open(raw_img)\n",
" draw = ImageDraw.Draw(img)\n",
" for text in texts:\n",
" st, ed = tuple(text['rectangle'][0]), tuple(text['rectangle'][1])\n",
" T = text['replacementText']\n",
" draw.rectangle((st, ed), fill='white')\n",
" font_size = proper_font_size(font_file, (ed[0] - st[0], ed[1] - st[1]), T, ratio=1)\n",
" font = ImageFont.truetype(font_file, font_size)\n",
" text_box = font.getbbox(T)\n",
" text_wh = (text_box[2] - text_box[0], text_box[3] - text_box[1])\n",
" cx, cy = (st[0] + ed[0]) // 2, st[1]\n",
" stx = cx - text_wh[0] // 2\n",
" sty = cy - text_wh[1] // 2\n",
" draw.text((stx, sty), T, font=font, fill='black')\n",
" img.save(tgt_img) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Process for no mask images\n",
"test_ids = set(mrlines(test_split_file))\n",
"\n",
"def detect_image_color(image):\n",
" gray_image = image.convert('L')\n",
" mean_brightness = np.mean(np.array(gray_image))\n",
" if mean_brightness < 127:\n",
" return 'white'\n",
" else:\n",
" return 'black'\n",
"\n",
"def cover_image(ann_path):\n",
" data = load(ann_path)\n",
" texts = list(data['text'].values())\n",
" raw_img = ann_path.replace('annotations', 'images').replace('.json', '')\n",
" tgt_img = raw_img.replace('images', 'images_abc')\n",
" img = Image.open(raw_img)\n",
" draw = ImageDraw.Draw(img)\n",
" color = detect_image_color(img)\n",
" font_size = 0\n",
" for text in texts:\n",
" st, ed = tuple(text['rectangle'][0]), tuple(text['rectangle'][1])\n",
" font_size += (ed[1] - st[1])\n",
" if len(texts) != 0:\n",
" font_size /= len(texts)\n",
" else:\n",
" font_size = 2\n",
" for text in texts:\n",
" st, ed = tuple(text['rectangle'][0]), tuple(text['rectangle'][1])\n",
" T = text['replacementText']\n",
" for i in range(2):\n",
" draw.rectangle(\n",
" [(st[0] - i, st[1] - i), (ed[0] + i, ed[1] + i)],\n",
" outline=color\n",
" )\n",
" font = ImageFont.truetype(font_file, font_size)\n",
" text_box = font.getbbox(T)\n",
" text_wh = (text_box[2] - text_box[0], text_box[3] - text_box[1])\n",
" cx, cy = (st[0] + ed[0]) // 2, st[1]\n",
" stx = cx - text_wh[0] // 2\n",
" sty = cy - text_wh[1] * 1.5\n",
" if sty < 0:\n",
" sty = cy + text_wh[1] * 1.3\n",
" draw.text((stx, sty), T, font=font, fill=color)\n",
" img.save(tgt_img) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"download_file('https://ai2-public-datasets.s3.amazonaws.com/diagrams/ai2d-all.zip')\n",
"os.system('unzip -o ai2d-all.zip')\n",
"\n",
"images = ls('ai2d/images/')\n",
"questions = ls('ai2d/questions/')\n",
"annotations = ls('ai2d/annotations/')\n",
"cates = load('ai2d/categories.json')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pool = mp.Pool(32)\n",
"pool.map(cover_image, annotations)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def puncproc(inText):\n",
" import re\n",
" outText = inText\n",
" punct = [\n",
" ';', r'/', '[', ']', '\"', '{', '}', '(', ')', '=', '+', '\\\\', '_', '-',\n",
" '>', '<', '@', '`', ',', '?', '!'\n",
" ]\n",
" commaStrip = re.compile('(\\d)(,)(\\d)') # noqa: W605\n",
" periodStrip = re.compile('(?!<=\\d)(\\.)(?!\\d)') # noqa: W605\n",
" for p in punct:\n",
" if (p + ' ' in inText or ' ' + p in inText) or (re.search(commaStrip, inText) is not None):\n",
" outText = outText.replace(p, '')\n",
" else:\n",
" outText = outText.replace(p, ' ')\n",
" outText = periodStrip.sub('', outText, re.UNICODE)\n",
" return outText\n",
"\n",
"def check_choices(line):\n",
" def ischar(s):\n",
" s = str(s)\n",
" if s in ['{}', 'Both', 'None of above']:\n",
" return True\n",
" elif s.startswith('Stage ') and ischar(s[6:]):\n",
" return True\n",
" elif ' and ' in s and np.all([ischar(x) for x in s.split(' and ')]):\n",
" return True\n",
" elif len(s) <= 2:\n",
" return True\n",
" elif len(puncproc(s).split()) > 1:\n",
" return np.all([ischar(x) for x in puncproc(s).split()])\n",
" return False\n",
" n_char = sum([ischar(line[x]) for x in 'ABCD'])\n",
" return n_char >= 3\n",
"\n",
"def check_question(question):\n",
" words = puncproc(question).split()\n",
" for ch in string.ascii_lowercase + string.ascii_uppercase:\n",
" if ch in words:\n",
" return True\n",
" return False\n",
"\n",
"def is_abc(abc, choices, question):\n",
" if abc == 0:\n",
" return False\n",
" if check_choices(choices):\n",
" return True\n",
" if check_question(question):\n",
" return True\n",
" return False"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data_all = defaultdict(list)\n",
"for qfile in questions:\n",
" data = load(qfile)\n",
" idx = data['imageName'].split('.')[0]\n",
" if idx not in test_ids:\n",
" continue\n",
" image_pth = qfile.replace('questions', 'images').replace('.json', '')\n",
" cate = cates[image_pth.split('/')[-1]]\n",
" for q, qmeta in data['questions'].items():\n",
" assert '.png-' in qmeta['questionId']\n",
" main, sub = qmeta['questionId'].split('.png-')\n",
" idx = int(main) * 100 + int(sub)\n",
" \n",
" answers = qmeta['answerTexts']\n",
" correct = qmeta['correctAnswer']\n",
" \n",
" data_all['index'].append(idx)\n",
" data_all['question'].append(q)\n",
" assert len(answers) == 4\n",
" for c, a in zip('ABCD', answers):\n",
" data_all[c].append(a)\n",
" data_all['answer'].append('ABCD'[qmeta['correctAnswer']])\n",
" data_all['category'].append(cate)\n",
" data_all['abcLabel'].append(qmeta['abcLabel'])\n",
" abc = is_abc(qmeta['abcLabel'], {x: data_all[x][-1] for x in 'ABCD'}, q)\n",
" # if qmeta['abcLabel'] and not abc:\n",
" # print(qmeta['abcLabel'], {x: data_all[x][-1] for x in 'ABCD'}, q)\n",
" data_all['image_path'].append(image_pth.replace('images', 'images_abc') if abc else image_pth)\n",
"data = pd.DataFrame(data_all)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"images = []\n",
"image_seen = {}\n",
"for idx, pth in zip(data['index'], data['image_path']):\n",
" images.append(encode_image_file_to_base64(pth))\n",
"\n",
"data['image'] = images\n",
"dump(data, 'AI2D_TEST.tsv')\n",
"print(md5('AI2D_TEST.tsv'))"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
+55
View File
@@ -0,0 +1,55 @@
import sys
from vlmeval import *
from vlmeval.dataset import SUPPORTED_DATASETS
FAIL_MSG = 'Failed to obtain answer via API.'
root = sys.argv[1]
if root[-1] in '/\\':
root = root[:-1]
model_name = root.split('/')[-1]
for d in SUPPORTED_DATASETS:
fname = f'{model_name}_{d}.xlsx'
pth = osp.join(root, fname)
if osp.exists(pth):
data = load(pth)
# Detect Failure
assert 'prediction' in data
data['prediction'] = [str(x) for x in data['prediction']]
fail = [FAIL_MSG in x for x in data['prediction']]
if sum(fail):
nfail = sum(fail)
ntot = len(fail)
print(f'Model {model_name} x Dataset {d}: {nfail} out of {ntot} failed. {nfail / ntot * 100: .2f}%. ')
eval_files = ls(root, match=f'{model_name}_{d}_')
eval_files = [x for x in eval_files if listinstr([f'{d}_openai', f'{d}_gpt'], x) and x.endswith('.xlsx')]
if len(eval_files) == 0:
print(f'Model {model_name} x Dataset {d} openai missing')
continue
assert len(eval_files) == 1
eval_file = eval_files[0]
data = load(eval_file)
if 'MMVet' in d:
bad = [x for x in data['log'] if 'All 5 retries failed.' in str(x)]
if len(bad):
print(f'Model {model_name} x Dataset {d} Evaluation: {len(bad)} out of {len(data)} failed.')
elif 'MathVista' in d:
bad = [x for x in data['res'] if FAIL_MSG in str(x)]
if len(bad):
print(f'Model {model_name} x Dataset {d} Evaluation: {len(bad)} out of {len(data)} failed.')
elif d == 'LLaVABench':
sub = data[data['gpt4_score'] == -1]
sub = sub[sub['gpt4_score'] == -1]
if len(sub):
print(f'Model {model_name} x Dataset {d} Evaluation: {len(sub)} out of {len(data)} failed.')
else:
bad = [x for x in data['log'] if FAIL_MSG in str(x)]
if len(bad):
print(f'Model {model_name} x Dataset {d} Evaluation: {len(bad)} out of {len(data)} failed.')
+38
View File
@@ -0,0 +1,38 @@
import argparse
from vlmeval.smp import *
from vlmeval.config import supported_VLM
def is_api(x):
return getattr(supported_VLM[x].func, 'is_api', False)
models = list(supported_VLM)
models = [x for x in models if 'fs' not in x]
models = [x for x in models if not is_api(x)]
exclude_list = ['cogvlm-grounding-generalist', 'emu2']
models = [x for x in models if x not in exclude_list]
def is_large(x):
return '80b' in x or 'emu2' in x or '34B' in x
small_models = [x for x in models if not is_large(x)]
large_models = [x for x in models if is_large(x)]
models = small_models + large_models
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, nargs='+', required=True)
args = parser.parse_args()
# Skip some models
models = [x for x in models if not listinstr(['MiniGPT', 'grounding-generalist'], x)]
for m in models:
unknown_datasets = [x for x in args.data if not osp.exists(f'{m}/{m}_{x}.xlsx')]
if len(unknown_datasets) == 0:
continue
dataset_str = ' '.join(unknown_datasets)
if '80b' in m:
cmd = f'python run.py --data {dataset_str} --model {m}'
else:
cmd = f'bash run.sh --data {dataset_str} --model {m}'
print(cmd)
os.system(cmd)
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cp $DIR/../config.py $DIR/../vlmeval/
cp $DIR/../misc/* $DIR/../vlmeval/vlm/misc/
+174
View File
@@ -0,0 +1,174 @@
"""
pip install gradio # proxy_on first
python vis_geochat_data.py
# browse data in http://127.0.0.1:10064
"""
import os
import io
import json
import copy
import time
import gradio as gr
import base64
from PIL import Image
from io import BytesIO
from argparse import Namespace
# from llava import conversation as conversation_lib
from typing import Sequence
from vlmeval import *
from vlmeval.dataset import SUPPORTED_DATASETS, build_dataset
SYS = "You are a helpful assistant. Your job is to faithfully translate all provided text into Chinese faithfully. "
# Translator = SiliconFlowAPI(model='Qwen/Qwen2.5-7B-Instruct', system_prompt=SYS)
Translator = OpenAIWrapper(model='gpt-4o-mini', system_prompt=SYS)
def image_to_mdstring(image):
return f"![image](data:image/jpeg;base64,{image})"
def images_to_md(images):
return '\n\n'.join([image_to_mdstring(image) for image in images])
def mmqa_display(question, target_size=2048):
question = {k.lower() if len(k) > 1 else k: v for k, v in question.items()}
keys = list(question.keys())
keys = [k for k in keys if k not in ['index', 'image']]
idx = question.pop('index', 'XXX')
text = f'\n- INDEX: {idx}\n'
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]
qtext = question.pop('question', None)
if qtext is not None:
text += f'- QUESTION: {qtext}\n'
if 'A' in question:
text += f'- Choices: \n'
for k in string.ascii_uppercase:
if k in question:
text += f'\t-{k}: {question.pop(k)}\n'
answer = question.pop('answer', None)
for k in question:
if not pd.isna(question[k]):
text += f'- {k.upper()}. {question[k]}\n'
if answer is not None:
text += f'- ANSWER: {answer}\n'
image_md = images_to_md(images)
return text, image_md
def parse_args():
parser = argparse.ArgumentParser()
# Essential Args, Setting the Names of Datasets and Models
parser.add_argument('--port', type=int, default=7860)
args = parser.parse_args()
return args
def gradio_app_vis_dataset(port=7860):
data, loaded_obj = None, {}
def btn_submit_click(filename, ann_id):
if filename not in loaded_obj:
return filename_change(filename, ann_id)
nonlocal data
data_desc = gr.Markdown(f'Visualizing {filename}, {len(data)} samples in total. ')
if ann_id < 0 or ann_id >= len(data):
return filename, ann_id, data_desc, gr.Markdown('Invalid Index'), gr.Markdown(f'Index out of range [0, {len(data) - 1}]')
item = data.iloc[ann_id]
text, image_md = mmqa_display(item)
return filename, ann_id, data_desc, image_md, text
def btn_next_click(filename, ann_id):
return btn_submit_click(filename, ann_id + 1)
# def translate_click(anno_en):
# return gr.Markdown(Translator.generate(anno_en))
def filename_change(filename, ann_id):
nonlocal data, loaded_obj
def legal_filename(filename):
LMURoot = LMUDataRoot()
if filename in SUPPORTED_DATASETS:
return build_dataset(filename).data
elif osp.exists(filename):
data = load(filename)
assert 'index' in data and 'image' in data
image_map = {i: image for i, image in zip(data['index'], data['image'])}
for k, v in image_map.items():
if (not isinstance(v, str) or len(v) < 64) and v in image_map:
image_map[k] = image_map[v]
data['image'] = [image_map[k] for k in data['index']]
return data
elif osp.exists(osp.join(LMURoot, filename)):
filename = osp.join(LMURoot, filename)
return legal_filename(filename)
else:
return None
data = legal_filename(filename)
if data is None:
return filename, 0, gr.Markdown(''), gr.Markdown("File not found"), gr.Markdown("File not found")
loaded_obj[filename] = data
return btn_submit_click(filename, 0)
with gr.Blocks() as app:
filename = gr.Textbox(
value='Dataset Name (supported by VLMEvalKit) or TSV FileName (Relative under `LMURoot` or Real Path)',
label='Dataset',
interactive=True,
visible=True)
with gr.Row():
ann_id = gr.Number(0, label='Sample Index (Press Enter)', interactive=True, visible=True)
btn_next = gr.Button("Next")
# btn_translate = gr.Button('CN Translate')
with gr.Row():
data_desc = gr.Markdown('Dataset Description', label='Dataset Description')
with gr.Row():
image_output = gr.Markdown('Image PlaceHolder', label='Image Visualization')
anno_en = gr.Markdown('Image Annotation', label='Image Annotation')
# anno_cn = gr.Markdown('Image Annotation (Chinese)', label='Image Annotation (Chinese)')
input_components = [filename, ann_id]
all_components = [filename, ann_id, data_desc, image_output, anno_en]
filename.submit(filename_change, input_components, all_components)
ann_id.submit(btn_submit_click, input_components, all_components)
btn_next.click(btn_next_click, input_components, all_components)
# btn_translate.click(translate_click, anno_en, anno_cn)
# app.launch()
app.launch(server_name='0.0.0.0', debug=True, show_error=True, server_port=port)
if __name__ == "__main__":
args = parse_args()
gradio_app_vis_dataset(port=args.port)
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
set -x
srun -n1 --ntasks-per-node=1 --partition $1 --gres=gpu:8 --quotatype=reserved --job-name vlmeval --cpus-per-task=64 torchrun --nproc-per-node=8 run.py ${@:2}
+114
View File
@@ -0,0 +1,114 @@
from vlmeval.smp import *
from vlmeval.dataset import SUPPORTED_DATASETS
def get_score(model, dataset):
file_name = f'{model}/{model}_{dataset}'
if listinstr([
'CCBench', 'MMBench', 'SEEDBench_IMG', 'MMMU', 'ScienceQA',
'AI2D_TEST', 'MMStar', 'RealWorldQA', 'BLINK', 'VisOnlyQA-VLMEvalKit'
], dataset):
file_name += '_acc.csv'
elif listinstr(['MME', 'Hallusion', 'LLaVABench'], dataset):
file_name += '_score.csv'
elif listinstr(['MMVet', 'MathVista'], dataset):
file_name += '_gpt-4-turbo_score.csv'
elif listinstr(['COCO', 'OCRBench'], dataset):
file_name += '_score.json'
elif listinstr(['Spatial457'], dataset):
file_name += '_score.json'
else:
raise NotImplementedError
if not osp.exists(file_name):
return {}
data = load(file_name)
ret = {}
if dataset == 'CCBench':
ret[dataset] = data['Overall'][0] * 100
elif dataset == 'MMBench':
for n, a in zip(data['split'], data['Overall']):
if n == 'dev':
ret['MMBench_DEV_EN'] = a * 100
elif n == 'test':
ret['MMBench_TEST_EN'] = a * 100
elif dataset == 'MMBench_CN':
for n, a in zip(data['split'], data['Overall']):
if n == 'dev':
ret['MMBench_DEV_CN'] = a * 100
elif n == 'test':
ret['MMBench_TEST_CN'] = a * 100
elif listinstr(['SEEDBench', 'ScienceQA', 'MMBench', 'AI2D_TEST', 'MMStar', 'RealWorldQA', 'BLINK'], dataset):
ret[dataset] = data['Overall'][0] * 100
elif 'MME' == dataset:
ret[dataset] = data['perception'][0] + data['reasoning'][0]
elif 'MMVet' == dataset:
data = data[data['Category'] == 'Overall']
ret[dataset] = float(data.iloc[0]['acc'])
elif 'HallusionBench' == dataset:
data = data[data['split'] == 'Overall']
for met in ['aAcc', 'qAcc', 'fAcc']:
ret[dataset + f' ({met})'] = float(data.iloc[0][met])
elif 'MMMU' in dataset:
data = data[data['split'] == 'validation']
ret['MMMU (val)'] = float(data.iloc[0]['Overall']) * 100
elif 'MathVista' in dataset:
data = data[data['Task&Skill'] == 'Overall']
ret[dataset] = float(data.iloc[0]['acc'])
elif 'LLaVABench' in dataset:
data = data[data['split'] == 'overall'].iloc[0]
ret[dataset] = float(data['Relative Score (main)'])
elif 'OCRBench' in dataset:
ret[dataset] = data['Final Score']
elif dataset == "VisOnlyQA-VLMEvalKit":
for n, a in zip(data['split'], data['Overall']):
ret[f'VisOnlyQA-VLMEvalKit_{n}'] = a * 100
elif 'Spatial457' in dataset:
ret["All"] = data["score"] * 100
for level in ["L1_single", "L2_objects", "L3_2d_spatial", "L4_occ",
"L4_pose", "L5_6d_spatial", "L5_collision"]:
ret[f"{dataset} - {level}"] = data[f"{level}_score"] * 100
return ret
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, nargs='+', default=[])
parser.add_argument("--model", type=str, nargs='+', required=True)
args = parser.parse_args()
return args
def gen_table(models, datasets):
res = defaultdict(dict)
for m in models:
for d in datasets:
try:
res[m].update(get_score(m, d))
except Exception as e:
logging.warning(f'{type(e)}: {e}')
logging.warning(f'Missing Results for Model {m} x Dataset {d}')
keys = []
for m in models:
for d in res[m]:
keys.append(d)
keys = list(set(keys))
keys.sort()
final = defaultdict(list)
for m in models:
final['Model'].append(m)
for k in keys:
if k in res[m]:
final[k].append(res[m][k])
else:
final[k].append(None)
final = pd.DataFrame(final)
dump(final, 'summ.csv')
if len(final) >= len(final.iloc[0].keys()):
print(tabulate(final))
else:
print(tabulate(final.T))
if __name__ == '__main__':
args = parse_args()
if args.data == []:
args.data = list(SUPPORTED_DATASETS)
gen_table(args.model, args.data)
+266
View File
@@ -0,0 +1,266 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import copy as cp\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.font_manager as fm\n",
"\n",
"def download_file(url, filename=None):\n",
" from urllib.request import urlretrieve\n",
" if filename is None:\n",
" filename = url.split('/')[-1]\n",
" urlretrieve(url, filename)\n",
"\n",
"font_URL = 'http://opencompass.openxlab.space/utils/Fonts/segoepr.ttf'\n",
"download_file(font_URL)\n",
"\n",
"font12 = fm.FontProperties(fname='segoepr.ttf', size=12)\n",
"font15 = fm.FontProperties(fname='segoepr.ttf', size=15, weight='bold')\n",
"font18 = fm.FontProperties(fname='segoepr.ttf', size=18, weight='bold')\n",
"\n",
"DATA_URL = 'http://opencompass.openxlab.space/utils/OpenVLM.json'\n",
"download_file(DATA_URL)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def pre_normalize(raw_data, labels):\n",
" data_list = cp.deepcopy(raw_data)\n",
" minimum, maximum, max_range, range_map = {}, {}, 0, {}\n",
" for lb in labels:\n",
" minimum[lb] = min([x[lb] for x in data_list])\n",
" maximum[lb] = max([x[lb] for x in data_list])\n",
" max_range = max(max_range, maximum[lb] - minimum[lb])\n",
" max_range *= 1.25\n",
" for lb in labels:\n",
" mid = (minimum[lb] + maximum[lb]) / 2\n",
" new_range = (mid - max_range / 2, mid + max_range / 2) if (mid + max_range / 2) < 100 else (100 - max_range, 100)\n",
" range_map[lb] = new_range\n",
" for item in data_list:\n",
" assert new_range[0] <= item[lb] <= new_range[1]\n",
" item[lb] = (item[lb] - new_range[0]) / max_range * 100\n",
" return data_list, range_map\n",
"\n",
"# solve the problem that some benchmark score is too high and out of range\n",
"def log_normalize(raw_data, labels):\n",
" data_list = cp.deepcopy(raw_data)\n",
" minimum, maximum, max_range, range_map = {}, {}, 0, {}\n",
" for lb in labels:\n",
" minimum[lb] = min([np.log(x[lb]) for x in data_list])\n",
" maximum[lb] = max([np.log(x[lb]) for x in data_list])\n",
" max_range = max(max_range, maximum[lb] - minimum[lb])\n",
" max_range *= 1.005\n",
" for lb in labels:\n",
" mid = (minimum[lb] + maximum[lb]) / 2\n",
" new_range = (mid - max_range / 2, mid + max_range / 2) if (mid + max_range / 2) < 100 else (100 - max_range, 100)\n",
" range_map[lb] = new_range\n",
" for item in data_list:\n",
" assert new_range[0] <= np.log(item[lb]) <= new_range[1]\n",
" item[lb] = (np.log(item[lb]) - new_range[0]) / max_range * 100\n",
" return data_list, range_map"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Draw MMBench Radar Graph\n",
"data = json.loads(open('OpenVLM.json').read())['results']\n",
"models = list(data)\n",
"print(models)\n",
"\n",
"# model2vis = [\n",
"# 'GPT-4v (detail: low)', 'GeminiProVision', 'Qwen-VL-Plus', \n",
"# 'InternLM-XComposer2-VL', 'LLaVA-v1.5-13B', 'CogVLM-17B-Chat',\n",
"# 'mPLUG-Owl2', 'Qwen-VL-Chat', 'IDEFICS-80B-Instruct'\n",
"# ]\n",
"\n",
"model2vis = [\n",
" # 'GPT-4v (detail: low)', 'GeminiProVision', 'InternLM-XComposer2-VL', \n",
" 'GPT-4v (1106, detail-low)', 'Gemini-1.0-Pro', 'Gemini-1.5-Pro', #'Gemini-1.5-Flash', 'Qwen-VL-Plus', \n",
" 'InternLM-XComposer2', 'LLaVA-v1.5-13B', 'CogVLM-17B-Chat',\n",
" 'mPLUG-Owl2', 'Qwen-VL-Chat', 'IDEFICS-80B-Instruct'\n",
"]\n",
"\n",
"colors = [\n",
" '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', \n",
" '#e377c2', '#7f7f7f', '#bcbd22'\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from collections import defaultdict\n",
"\n",
"split = 'MMBench_TEST_EN'\n",
"# data_sub = {k: v[split] for k, v in data.items()}\n",
"data_sub = {k: defaultdict(int, v)[split] for k, v in data.items()}\n",
"# solve the problem that some model lack the evaluation of MMBench_TEST_EN\n",
"\n",
"labels = list(data_sub[model2vis[0]])\n",
"labels.remove('Overall')\n",
"num_vars = len(labels)\n",
"\n",
"raw_data = [data_sub[m] for m in model2vis]\n",
"data_list, range_map = pre_normalize(raw_data, labels)\n",
"\n",
"alpha = 0.25\n",
"angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()\n",
"angles_deg = np.linspace(0, 360, num_vars, endpoint=False).tolist()\n",
"fig, ax_base = plt.subplots(nrows=1, ncols=1, figsize=(10, 10), subplot_kw=dict(polar=True))\n",
"\n",
"for i in range(len(data_list)):\n",
" item = data_list[i]\n",
" model_name = model2vis[i]\n",
" color = colors[i]\n",
" tmp_angles = angles[:] + [angles[0]]\n",
" tmp_values = [item[lb] for lb in labels] + [item[labels[0]]]\n",
" ax_base.plot(tmp_angles, tmp_values, color=color, linewidth=1, linestyle='solid', label=model_name)\n",
" ax_base.fill(tmp_angles, tmp_values, color=color, alpha=alpha)\n",
" \n",
"angles += [angles[0]]\n",
"ax_base.set_ylim(0, 100)\n",
"ax_base.set_yticks([40, 60, 80, 100])\n",
"ax_base.set_yticklabels([''] * 4)\n",
"\n",
"ax_base.tick_params(pad=25)\n",
"ax_base.set_xticks(angles[:-1])\n",
"ax_base.set_xticklabels(labels, fontproperties=font18)\n",
"\n",
"leg = ax_base.legend(loc='center right', bbox_to_anchor=(1.6, 0.5), prop=font15, ncol=1, frameon=True, labelspacing=1.2)\n",
"for line in leg.get_lines():\n",
" line.set_linewidth(2.5)\n",
"\n",
"cx, cy, sz = 0.44, 0.435, 0.34\n",
"axes = [fig.add_axes([cx - sz, cy - sz, cx + sz, cy + sz], projection='polar', label='axes%d' % i) for i in range(num_vars)]\n",
" \n",
"for ax, angle, label in zip(axes, angles_deg, labels):\n",
" ax.patch.set_visible(False)\n",
" ax.grid(False)\n",
" ax.xaxis.set_visible(False)\n",
" cur_range = range_map[label]\n",
" label_list = [cur_range[0] + (cur_range[1] - cur_range[0]) / 5 * i for i in range(2, 6)]\n",
" label_list = [f'{x:.1f}' for x in label_list]\n",
" ax.set_rgrids(range(40, 120, 20), angle=angle, labels=label_list, font_properties=font12)\n",
" ax.spines['polar'].set_visible(False)\n",
" ax.set_ylim(0, 100)\n",
"\n",
"title_text = f'{len(model2vis)} Representative VLMs on MMBench Test.'\n",
"plt.figtext(.7, .95, title_text, fontproperties=font18, ha='center')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"labels = ['SEEDBench_IMG', 'CCBench', 'MMBench_TEST_EN', 'MMBench_TEST_CN', 'MME', 'MMVet', 'MMMU_VAL', 'MathVista', 'HallusionBench', 'LLaVABench']\n",
"num_vars = len(labels)\n",
"\n",
"raw_data = [{k: data[m][k]['Overall'] for k in labels} for m in model2vis]\n",
"data_list, range_map = pre_normalize(raw_data, labels)\n",
"\n",
"alpha = 0.25\n",
"angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()\n",
"angles_deg = np.linspace(0, 360, num_vars, endpoint=False).tolist()\n",
"fig, ax_base = plt.subplots(nrows=1, ncols=1, figsize=(10, 10), subplot_kw=dict(polar=True))\n",
"\n",
"for i in range(len(data_list)):\n",
" item = data_list[i]\n",
" model_name = model2vis[i]\n",
" color = colors[i]\n",
" tmp_angles = angles[:] + [angles[0]]\n",
" tmp_values = [item[lb] for lb in labels] + [item[labels[0]]]\n",
" ax_base.plot(tmp_angles, tmp_values, color=color, linewidth=1, linestyle='solid', label=model_name)\n",
" ax_base.fill(tmp_angles, tmp_values, color=color, alpha=alpha)\n",
" \n",
"angles += [angles[0]]\n",
"ax_base.set_ylim(0, 100)\n",
"ax_base.set_yticks([40, 60, 80, 100])\n",
"ax_base.set_yticklabels([''] * 4)\n",
"\n",
"ax_base.tick_params(pad=15)\n",
"ax_base.set_xticks(angles[:-1])\n",
"ax_base.set_xticklabels(labels, fontproperties=font18)\n",
"\n",
"dataset_map = {\n",
" 'MMBench_TEST_EN': 'MMBench (Test)', \n",
" 'MMBench_TEST_CN': 'MMBenchCN (Test)', \n",
" 'MathVista': 'MathVista (TestMini)', \n",
" 'MMMU_VAL': 'MMMU (Val)'\n",
"}\n",
"for i, label in enumerate(ax_base.get_xticklabels()):\n",
" x,y = label.get_position()\n",
" text = label.get_text()\n",
" text = dataset_map[text] if text in dataset_map else text\n",
" lab = ax_base.text(x, y, text, transform=label.get_transform(),\n",
" ha=label.get_ha(), va=label.get_va(), font_properties=font15)\n",
" lab.set_rotation(360 / num_vars * i + 270)\n",
" labels.append(lab)\n",
"ax_base.set_xticklabels([])\n",
"\n",
"leg = ax_base.legend(loc='center right', bbox_to_anchor=(1.6, 0.5), prop=font15, ncol=1, frameon=True, labelspacing=1.2)\n",
"for line in leg.get_lines():\n",
" line.set_linewidth(2.5)\n",
"\n",
"cx, cy, sz = 0.44, 0.435, 0.34\n",
"axes = [fig.add_axes([cx - sz, cy - sz, cx + sz, cy + sz], projection='polar', label='axes%d' % i) for i in range(num_vars)]\n",
" \n",
"for ax, angle, label in zip(axes, angles_deg, labels):\n",
" ax.patch.set_visible(False)\n",
" ax.grid(False)\n",
" ax.xaxis.set_visible(False)\n",
" cur_range = range_map[label]\n",
" label_list = [cur_range[0] + (cur_range[1] - cur_range[0]) / 5 * i for i in range(2, 6)]\n",
" label_list = [f'{x:.1f}' for x in label_list]\n",
" ax.set_rgrids(range(40, 120, 20), angle=angle, labels=label_list, font_properties=font12)\n",
" ax.spines['polar'].set_visible(False)\n",
" ax.set_ylim(0, 100)\n",
"\n",
"title_text = f'{len(model2vis)} Representative VLMs on {num_vars} Benchmarks in OpenCompass Multi-Modal Leaderboard.'\n",
"plt.figtext(.7, .95, title_text, fontproperties=font18, ha='center')\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
+122
View File
@@ -0,0 +1,122 @@
import re
import sys
from os.path import exists
from setuptools import find_packages, setup
def parse_requirements(fname='requirements.txt', with_version=True):
"""Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
List[str]: list of requirements items
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
require_fpath = fname
def parse_line(line):
"""Parse information from a line in a requirements text file."""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
elif '@git+' in line:
info['package'] = line
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info
def parse_require_file(fpath):
with open(fpath, 'r') as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
for info in parse_line(line):
yield info
def gen_packages_items():
if exists(require_fpath):
for info in parse_require_file(require_fpath):
parts = [info['package']]
if with_version and 'version' in info:
parts.extend(info['version'])
if not sys.version.startswith('3.4'):
# apparently package_deps are broken in 3.4
platform_deps = info.get('platform_deps')
if platform_deps is not None:
parts.append(';' + platform_deps)
item = ''.join(parts)
yield item
packages = list(gen_packages_items())
return packages
with open('README.md') as f:
readme = f.read()
def do_setup():
setup(
name='vlmeval',
version='0.1.0',
description='OpenCompass VLM Evaluation Kit',
author='Haodong Duan',
author_email='dhd.efz@gmail.com',
maintainer='Haodong Duan',
maintainer_email='dhd.efz@gmail.com',
long_description=readme,
long_description_content_type='text/markdown',
cmdclass={},
install_requires=parse_requirements('requirements.txt'),
setup_requires=[],
python_requires='>=3.7.0',
packages=find_packages(exclude=[
'test*',
'paper_test*',
]),
keywords=['AI', 'NLP', 'in-context learning'],
entry_points={
'console_scripts': ['vlmutil = vlmeval:cli']
},
classifiers=[
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
])
if __name__ == '__main__':
do_setup()
+20
View File
@@ -0,0 +1,20 @@
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# Temporarily bypass SSL certificate verification to download files from oss.
try:
import torch
except ImportError:
pass
from .smp import *
from .api import *
from .dataset import *
from .utils import *
from .vlm import *
from .config import *
from .tools import cli
load_env()
__version__ = '0.2rc1'
+29
View File
@@ -0,0 +1,29 @@
from .gpt import OpenAIWrapper, GPT4V
from .hf_chat_model import HFChatModel
from .gemini import GeminiWrapper, Gemini
from .qwen_vl_api import QwenVLWrapper, QwenVLAPI, Qwen2VLAPI
from .qwen_api import QwenAPI
from .claude import Claude_Wrapper, Claude3V
from .reka import Reka
from .glm_vision import GLMVisionAPI
from .cloudwalk import CWWrapper
from .sensechat_vision import SenseChatVisionAPI
from .siliconflow import SiliconFlowAPI, TeleMMAPI
from .hunyuan import HunyuanVision
from .bailingmm import bailingMMAPI
from .bluelm_v_api import BlueLMWrapper, BlueLM_V_API
from .jt_vl_chat import JTVLChatAPI
from .taiyi import TaiyiAPI
from .lmdeploy import LMDeployAPI
from .taichu import TaichuVLAPI, TaichuVLRAPI
from .doubao_vl_api import DoubaoVL
from .mug_u import MUGUAPI
__all__ = [
'OpenAIWrapper', 'HFChatModel', 'GeminiWrapper', 'GPT4V', 'Gemini',
'QwenVLWrapper', 'QwenVLAPI', 'QwenAPI', 'Claude3V', 'Claude_Wrapper',
'Reka', 'GLMVisionAPI', 'CWWrapper', 'SenseChatVisionAPI', 'HunyuanVision',
'Qwen2VLAPI', 'BlueLMWrapper', 'BlueLM_V_API', 'JTVLChatAPI',
'bailingMMAPI', 'TaiyiAPI', 'TeleMMAPI', 'SiliconFlowAPI', 'LMDeployAPI',
'TaichuVLAPI', 'TaichuVLRAPI', 'DoubaoVL', "MUGUAPI"
]
+91
View File
@@ -0,0 +1,91 @@
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,
wait: 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__(wait=wait, 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)
+290
View File
@@ -0,0 +1,290 @@
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']
INTERLEAVE = True
INSTALL_REQ = False
def __init__(self,
retry=10,
wait=3,
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 3.
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:
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 '<image>' 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
Loaded 100 of 510 files, more files were not shown because too many files have changed in this diff. Show more