Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Shapegrid/ShapeGrid_dis.parquetAdded+3
- Shapegrid/ShapeGrid_loc.parquetAdded+3
- VLMEvalKit-sudoku/.github/scripts/assert_score.pyAdded+61
- VLMEvalKit-sudoku/.github/workflows/lint.ymlAdded+23
- VLMEvalKit-sudoku/.github/workflows/pr-run-test.ymlAdded+70
- VLMEvalKit-sudoku/llava/serve/__init__.pyAdded
- VLMEvalKit-sudoku/llava/serve/examples/extreme_ironing.jpgAdded
- VLMEvalKit-sudoku/llava/train/train_dpo.pyAdded+1782
- VLMEvalKit-sudoku/requirements/docs.txtAdded+11
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/claude.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/gemini.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/glm_vision.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/hf_chat_model.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/hunyuan.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/lmdeploy.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/api/__pycache__/qwen_vl_api.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/megabench.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/sfebench.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/cmmmu.pyAdded+354
- VLMEvalKit-sudoku/vlmeval/dataset/creation.pyAdded+741
- VLMEvalKit-sudoku/vlmeval/dataset/dude.pyAdded+211
- VLMEvalKit-sudoku/vlmeval/dataset/image_mcq.pyAdded
- VLMEvalKit-sudoku/vlmeval/dataset/m4bench.pyAdded+193
- VLMEvalKit-sudoku/vlmeval/dataset/miabench.pyAdded+166
- VLMEvalKit-sudoku/vlmeval/dataset/mmbench_video.pyAdded+257
- VLMEvalKit-sudoku/vlmeval/dataset/mmifeval.pyAdded+483
- VLMEvalKit-sudoku/vlmeval/dataset/qbench_video.pyAdded+354
- VLMEvalKit-sudoku/vlmeval/dataset/text_base.pyAdded+88
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/mlvu.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/multiple_choice.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/omni_verifier.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/shortqa.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/spatial457.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/tamperbench.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/tempcompass.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/yorn.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/README.mdAdded+51
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__init__.pyAdded+5
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__pycache__/evaluator.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__pycache__/response_parse_type.cpython-310.pycAdded
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/aggregation/min_agg.pyAdded+14
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/aggregation_type.pyAdded+25
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/evaluator.pyAdded+399
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/metric_type.pyAdded+259
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/answer_str_parse.pyAdded+137
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/dummy_parse.pyAdded+6
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/json_parse.pyAdded+17
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/requirements.txtAdded+15
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/response_parse_type.pyAdded+54
- VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/scoring/nli_entailment.pyAdded+20
123version https://git-lfs.github.com/spec/v1oid sha256:c16d47667c9c5d2a97d70370610e54733861ec9043f2bb8aa6107c927de2367dsize 102012404123version https://git-lfs.github.com/spec/v1oid sha256:8549444eaf072e051373241edca5e00a5d141c012c9a33fee6f353c3e203abc4size 6616618812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import argparseimport astimport jsonimport 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()1234567891011121314151617181920212223name: 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-files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970name: pr_run_test
on: pull_request: branches: - "main" paths-ignore: - "docs/**" - "**.md" workflow_dispatch: schedule: - cron: '56 01 * * *'
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.89090909,"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.7975708502024291,"InternVL2_5-8B":0.854251012145749,"llava_onevision_qwen2_7b_si":0.8178137651821862},"OCRBench_MINI":{"Qwen2-VL-7B-Instruct":16.6,"InternVL2_5-8B":16.7,"llava_onevision_qwen2_7b_si":13.0}}' HF_HUB_CACHE: /fs-computility/llm/shared/llmeval/models/opencompass_hf_hub HF_HUB_OFFLINE: 1 CONDA_PATH: /fs-computility/llm/qa-llm-cicd/miniconda3 CONDA_ENV: vlm_pr_test
jobs: vlm_test: if: ${{!cancelled()}} runs-on: [volc_cu12_mllm] 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"] steps: - name: clone_repo uses: actions/checkout@v3 - name: evaluation_model uses: nick-fields/retry@v3 with: max_attempts: 3 timeout_minutes: 30 command: | . ${{env.CONDA_PATH}}/bin/activate conda activate ${{env.CONDA_ENV}} pip uninstall vlmeval -y pip install -e . pre_model=$(echo ${{matrix.model}} | awk -F'/' '{print $1}') 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 pip list nvidia-smi LOG=$(python run.py --data ${{matrix.dataset}} --model $model_name 2>&1) echo "$LOG" if echo "$LOG" | grep -q "CUDA out of memory"; then sleep 300 exit 1 # retry becuase of oom fi - name: assert_result run: | . ${{env.CONDA_PATH}}/bin/activate conda activate ${{env.CONDA_ENV}} 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 python .github/scripts/assert_score.py --dataset "${{matrix.dataset}}" --base_score $BASE_SCORE --model-name $model_name123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li## 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.
import osimport copyimport deepspeedfrom dataclasses import dataclass, fieldimport jsonimport loggingimport pathlibfrom typing import Dict, Optional, Sequence, Listimport ast
import yamlimport timeimport randomimport yamlimport mathimport reimport torch
import transformersimport tokenizers
from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEXfrom torch.utils.data import Datasetfrom llava.train.llava_trainer import LLaVADPOTrainerfrom data_processing.utils import load_jsonl, load_jsonfrom llava import conversation as conversation_libfrom llava.model import *from llava.model.language_model.llava_qwen import LlavaQwenConfigfrom llava.model.language_model.llava_llama import LlavaConfigfrom llava.model.language_model.llava_mistral import LlavaMistralConfigfrom llava.mm_utils import process_highres_image, process_anyres_image, process_highres_image_crop_split, tokenizer_image_tokenfrom llava.utils import rank0_printfrom transformers import AutoConfigimport pickle
from trl.trainer.utils import DPODataCollatorWithPaddingfrom PIL import Image, ImageFilefrom decord import VideoReader, cpu
ImageFile.LOAD_TRUNCATED_IMAGES = Truefrom packaging import versionfrom typing import Any
local_rank = Noneimport numpy as np
IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse("0.14")
@dataclassclass ModelArguments: model_name_or_path: Optional[str] = field(default="facebook/opt-125m") model_class_name: Optional[str] = field(default=None, metadata={"help": "Used to init model class, format is XXXXForCausalLM. e.g. currently XXXX is chosen from LlavaLlama, LlavaMixtral, LlavaMistral, Llama"})
mm_tunable_parts: Optional[str] = field( default=None, metadata={"help": 'Could be "mm_mlp_adapter", "mm_vision_resampler", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_vision_tower,mm_mlp_adapter,mm_language_model", "mm_mlp_adapter,mm_language_model"'} ) # deciding which part of the multimodal model to tune, will overwrite other previous settings
version: Optional[str] = field(default="v0") freeze_backbone: bool = field(default=False) tune_mm_mlp_adapter: bool = field(default=False) tune_mm_vision_resampler: bool = field(default=False) vision_tower: Optional[str] = field(default=None) vision_tower_pretrained: Optional[str] = field(default=None) # default to the last layer
unfreeze_mm_vision_tower: bool = field(default=False) unfreeze_language_model: bool = field(default=False) mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer pretrain_mm_mlp_adapter: Optional[str] = field(default=None) mm_projector_type: Optional[str] = field(default="linear") mm_use_im_start_end: bool = field(default=False) mm_use_im_patch_token: bool = field(default=True) mm_patch_merge_type: Optional[str] = field(default="flat") mm_vision_select_feature: Optional[str] = field(default="patch") mm_resampler_type: Optional[str] = field(default=None) mm_mask_drop_mode: str = field(default="fixed") mm_mask_drop_skip_percentage: float = field(default=0.0) mm_mask_drop_ratio: float = field(default=0.25) mm_mask_drop_ratio_upper: Optional[float] = field(default=None) mm_mask_drop_ratio_lower: Optional[float] = field(default=None) mm_spatial_pool_stride: Optional[int] = field(default=None) mm_spatial_pool_mode: str = field(default="average") mm_spatial_pool_out_channels: Optional[int] = field(default=None) mm_perceiver_depth: Optional[int] = field(default=3) mm_perceiver_latents: Optional[int] = field(default=32) mm_perceiver_ff_mult: Optional[float] = field(default=4) mm_perceiver_pretrained: Optional[str] = field(default=None) mm_qformer_depth: Optional[int] = field(default=3) mm_qformer_latents: Optional[int] = field(default=32) mm_qformer_pretrained: Optional[str] = field(default=None)
rope_scaling_factor: Optional[float] = field(default=None) rope_scaling_type: Optional[str] = field(default=None)
s2: Optional[bool] = field(default=False) s2_scales: Optional[str] = field(default="336,672,1008")
@dataclassclass DataArguments: data_path: str = field(default=None, metadata={"help": "Path to the training data, in llava's instruction.json format. Supporting multiple json files via /path/to/{a,b,c}.json"}) lazy_preprocess: bool = False is_multimodal: bool = False image_folder: Optional[str] = field(default=None) video_folder: Optional[str] = field(default=None) video_fps: Optional[int] = field(default=1) image_aspect_ratio: str = "square" image_grid_pinpoints: Optional[str] = field(default=None) image_crop_resolution: int = 384 image_split_resolution: int = 384 input_prompt: Optional[str] = field(default=None) refine_prompt: Optional[bool] = field(default=False) frames_upbound: Optional[int] = field(default=0) num_sample: Optional[int] = field(default=None)
@dataclassclass TrainingArguments(transformers.TrainingArguments): cache_dir: Optional[str] = field(default=None) optim: str = field(default="adamw_torch") remove_unused_columns: bool = field(default=False) freeze_mm_mlp_adapter: bool = field(default=False) freeze_mm_vision_resampler: bool = field(default=False) mpt_attn_impl: Optional[str] = field(default="triton") model_max_length: int = field( default=4096, metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."}, ) double_quant: bool = field(default=True, metadata={"help": "Compress the quantization statistics through double quantization."}) quant_type: str = field(default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}) bits: int = field(default=16, metadata={"help": "How many bits to use."}) lora_enable: bool = False lora_r: int = 64 lora_alpha: int = 16 lora_dropout: float = 0.05 lora_weight_path: str = "" lora_bias: str = "none" mm_projector_lr: Optional[float] = None mm_vision_tower_lr: Optional[float] = None group_by_varlen: bool = field(default=False) group_by_modality_length: bool = field(default=False) group_by_modality_length_auto: bool = field(default=False) auto_find_batch_size: bool = field(default=False) gradient_checkpointing: bool = field(default=True) verbose_logging: bool = field(default=False) attn_implementation: str = field(default="flash_attention_2", metadata={"help": "Use transformers attention implementation."}) dpo_alpha: float = field(default=1.0) beta: float = field(default=0.1) gamma: float = field(default=1.0) generate_during_eval: bool = field(default=False) precompute_ref_log_probs: bool = field(default=False)
def maybe_zero_3(param, ignore_status=False, name=None): from deepspeed import zero from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
if hasattr(param, "ds_id"): if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: if not ignore_status: logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") with zero.GatheredParameters([param]): param = param.data.detach().cpu().clone() else: param = param.detach().cpu().clone() return param
# Borrowed from peft.utils.get_peft_model_state_dictdef get_peft_state_maybe_zero_3(named_params, bias): if bias == "none": to_return = {k: t for k, t in named_params if "lora_" in k} elif bias == "all": to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} elif bias == "lora_only": to_return = {} maybe_lora_bias = {} lora_bias_names = set() for k, t in named_params: if "lora_" in k: to_return[k] = t bias_name = k.split("lora_")[0] + "bias" lora_bias_names.add(bias_name) elif "bias" in k: maybe_lora_bias[k] = t for k, t in maybe_lora_bias: if bias_name in lora_bias_names: to_return[bias_name] = t else: raise NotImplementedError to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()} return to_return
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): to_return = {k: t for k, t in named_params if "lora_" not in k} if require_grad_only: to_return = {k: t for k, t in to_return.items() if t.requires_grad} to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} return to_return
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} return to_return
def find_all_linear_names(model): cls = torch.nn.Linear lora_module_names = set() multimodal_keywords = ["mm_projector", "vision_tower", "vision_resampler"] for name, module in model.named_modules(): if any(mm_keyword in name for mm_keyword in multimodal_keywords): continue if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1])
if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names)
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): """Collects the state dict and dump to disk.""" if hasattr(trainer.args, "tune_mm_mlp_adapter") and trainer.args.tune_mm_mlp_adapter: check_only_save_mm_adapter_tunnable = True # only has mm_mlp_adapter and mm_vision_resampler in the tuneable parts elif hasattr(trainer.args, "mm_tunable_parts") and (len(trainer.args.mm_tunable_parts.split(",")) == 1 and ("mm_mlp_adapter" in trainer.args.mm_tunable_parts or "mm_vision_resampler" in trainer.args.mm_tunable_parts)): check_only_save_mm_adapter_tunnable = True else: check_only_save_mm_adapter_tunnable = False
trainer.accelerator.wait_for_everyone() torch.cuda.synchronize() rank0_print(f"Only save projectors: {check_only_save_mm_adapter_tunnable}") if check_only_save_mm_adapter_tunnable: # Only save Adapter keys_to_match = ["mm_projector", "vision_resampler"] if getattr(trainer.args, "use_im_start_end", False): keys_to_match.extend(["embed_tokens", "embed_in"])
weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) trainer.model.config.save_pretrained(output_dir)
current_folder = output_dir.split("/")[-1] parent_folder = os.path.dirname(output_dir) if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: if current_folder.startswith("checkpoint-"): mm_projector_folder = os.path.join(parent_folder, "mm_projector") os.makedirs(mm_projector_folder, exist_ok=True) torch.save(weight_to_save, os.path.join(mm_projector_folder, f"{current_folder}.bin")) else: torch.save(weight_to_save, os.path.join(output_dir, f"mm_projector.bin")) return
if trainer.deepspeed: trainer.save_model(output_dir) return
state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()} del state_dict trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
def smart_tokenizer_and_embedding_resize( special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel,): """Resize tokenizer and embedding.
Note: This is the unoptimized version that may make your embedding size not be divisible by 64. """ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer))
if num_new_tokens > 0: input_embeddings = model.get_input_embeddings().weight.data output_embeddings = model.get_output_embeddings().weight.data
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True) output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
input_embeddings[-num_new_tokens:] = input_embeddings_avg output_embeddings[-num_new_tokens:] = output_embeddings_avg
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] input_ids_lens = labels_lens = [tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, )
def _mask_targets(target, tokenized_lens, speakers): # cur_idx = 0 cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for tokenized_len, speaker in zip(tokenized_lens, speakers): if speaker == "human": target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX cur_idx += tokenized_len
def _add_speaker_and_signal(header, source, get_conversation=True): """Add speaker and start/end signal on each round.""" BEGIN_SIGNAL = "### " END_SIGNAL = "\n" conversation = header for sentence in source: from_str = sentence["from"] if from_str.lower() == "human": from_str = conversation_lib.default_conversation.roles[0] elif from_str.lower() == "gpt": from_str = conversation_lib.default_conversation.roles[1] else: from_str = "unknown" sentence["value"] = BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL if get_conversation: conversation += sentence["value"] conversation += BEGIN_SIGNAL return conversation
def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: return sources
for source in sources: for sentence in source: if DEFAULT_IMAGE_TOKEN in sentence["value"] and not sentence["value"].startswith(DEFAULT_IMAGE_TOKEN): sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"] sentence["value"] = sentence["value"].strip() if "mmtag" in conversation_lib.default_conversation.version: sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>") replace_token = DEFAULT_IMAGE_TOKEN if data_args.mm_use_im_start_end: replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
return sources
def preprocess_multimodal_movie(sources: Sequence[str], data_args: DataArguments, video_inputs: str) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: return sources
for source in sources: for sentence in source: if DEFAULT_IMAGE_TOKEN in sentence["value"]: prompt = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip() replace_token = video_inputs if data_args.mm_use_im_start_end: replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
return sources, prompt
def preprocess_llama_2(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:]
conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt())
# Tokenize conversations
if has_image: input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids
targets = input_ids.clone()
assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
# Mask targets sep = "[/INST] " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum())
rounds = conversation.split(conv.sep2) cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(rounds): if rou == "": break
parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep
if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 2
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
cur_len += round_len target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
return dict( input_ids=input_ids, labels=targets, )
def make_conv(prompt, answer): return [ { "from": "human", "value": prompt, }, { "from": "gpt", "value": answer, }, ]
def preprocess_gemma(sources: List[List[Dict[str, str]]], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: conv: conversation_lib.Conversation = conversation_lib.default_conversation.copy() roles: Dict[str, str] = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates conversations: List[str] = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source: List[Dict[str, str]] = source[1:]
conv.messages = [] for j, sentence in enumerate(source): role: str = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt())
# Tokenize conversations if has_image: input_ids: torch.Tensor = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) else: input_ids: torch.Tensor = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids
targets: torch.Tensor = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.GEMMA
# Mask target sep: str = conv.sep + conv.roles[1] for conversation, target in zip(conversations, targets): total_len: int = int(target.ne(tokenizer.pad_token_id).sum())
rounds: List[str] = conversation.split(conv.sep) re_rounds = [] for conv_idx in range(0, len(rounds), 2): re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2]))
cur_len = 1 # Ignore <bos> target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(re_rounds): if rou == "": break
parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep # Re-append sep because split on this # Now "".join(parts)==rou
if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) - 1 # Ignore <bos> instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 # Ignore <bos> else: round_len = len(tokenizer(rou).input_ids) - 1 # Ignore <bos> instruction_len = len(tokenizer(parts[0]).input_ids) - 1 # Ignore <bos>
round_len += 2 # sep: <end_of_turn>\n takes 2 tokens target[cur_len : cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len
target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX rank0_print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
return dict( input_ids=input_ids, labels=targets, )
def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict: roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"}
im_start, im_end = tokenizer.additional_special_tokens_ids nl_tokens = tokenizer("\n").input_ids _system = tokenizer("system").input_ids + nl_tokens _user = tokenizer("user").input_ids + nl_tokens _assistant = tokenizer("assistant").input_ids + nl_tokens
# Apply prompt templates input_ids, targets = [], [] for i, source in enumerate(sources): if roles[source[0]["from"]] != roles["human"]: source = source[1:]
input_id, target = [], [] system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens input_id += system target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens assert len(input_id) == len(target) for j, sentence in enumerate(source): role = roles[sentence["from"]] if has_image and "<image>" in sentence["value"]: assert sentence["value"].startswith("<image>"), print(sentence["value"])
_input_id = tokenizer(role).input_ids + nl_tokens + [IMAGE_TOKEN_INDEX] + nl_tokens + tokenizer(sentence["value"][len("<image>") :]).input_ids + [im_end] + nl_tokens else: _input_id = tokenizer(role).input_ids + nl_tokens + tokenizer(sentence["value"]).input_ids + [im_end] + nl_tokens input_id += _input_id if role == "<|im_start|>user": _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens elif role == "<|im_start|>assistant": _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens else: raise NotImplementedError target += _target assert len(input_id) == len(target) # input_id += [tokenizer.pad_token_id] * (max_len - len(input_id)) # target += [IGNORE_INDEX] * (max_len - len(target)) input_ids.append(input_id) targets.append(target) input_ids = torch.tensor(input_ids, dtype=torch.long) targets = torch.tensor(targets, dtype=torch.long)
return dict( input_ids=input_ids, # tensor(bs x seq_len) labels=targets, # tensor(bs x seq_len) # attention_mask=input_ids.ne(tokenizer.pad_token_id), # tensor(bs x seq_len) )
def preprocess_llama3( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.",) -> Dict: roles = {"human": "<|start_header_id|>user<|end_header_id|>", "gpt": "<|start_header_id|>assistant<|end_header_id|>"}
eot_id = tokenizer.convert_tokens_to_ids("<|eot_id|>") nl_tokens = tokenizer("\n").input_ids
# Apply prompt templates input_ids, targets = [], [] for i, source in enumerate(sources): if roles[source[0]["from"]] != roles["human"]: source = source[1:]
input_id, target = [], [] system = tokenizer("<|begin_of_text|>").input_ids + tokenizer("<|start_header_id|>system<|end_header_id|>").input_ids + nl_tokens * 2 + tokenizer(system_message).input_ids + [eot_id] input_id += system target += [IGNORE_INDEX] * len(system) for j, sentence in enumerate(source): role = roles[sentence["from"]] if has_image and "<image>" in sentence["value"]: assert sentence["value"].startswith("<image>"), print(sentence["value"]) _input_id = tokenizer(role).input_ids + nl_tokens * 2 + [IMAGE_TOKEN_INDEX] + tokenizer(sentence["value"][len("<image>") :]).input_ids + [eot_id] else: _input_id = tokenizer(role).input_ids + nl_tokens * 2 + tokenizer(sentence["value"]).input_ids + [eot_id] input_id += _input_id if role == "<|start_header_id|>user<|end_header_id|>": _target = [IGNORE_INDEX] * len(_input_id) elif role == "<|start_header_id|>assistant<|end_header_id|>": _target = [IGNORE_INDEX] * (len(tokenizer(role).input_ids) + 2) + _input_id[len(tokenizer(role).input_ids) + 2 : -1] + [eot_id] else: raise NotImplementedError target += _target assert len(input_id) == len(target), f"{len(input_id)} != {len(target)}" input_ids.append(input_id) targets.append(target) input_ids = torch.tensor(input_ids, dtype=torch.long) targets = torch.tensor(targets, dtype=torch.long)
return dict( input_ids=input_ids, # tensor(bs x seq_len) labels=targets, # tensor(bs x seq_len) )
def preprocess_v1(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:]
conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt())
# Tokenize conversations
if has_image: input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids
targets = input_ids.clone()
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
# Mask targets sep = conv.sep + conv.roles[1] + ": " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum())
rounds = conversation.split(conv.sep2) cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(rounds): if rou == "": break
parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep
if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 2
if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14: round_len -= 1 instruction_len -= 1
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
cur_len += round_len target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)")
return dict( input_ids=input_ids, labels=targets, )
def preprocess_mpt(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:]
conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt())
# Tokenize conversations
if has_image: input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids
targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
# Mask targets sep = conv.sep + conv.roles[1] for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum())
rounds = conversation.split(conv.sep) re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt for conv_idx in range(3, len(rounds), 2): re_rounds.append(conv.sep.join(rounds[conv_idx : conv_idx + 2])) # user + gpt cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(re_rounds): if rou == "": break
parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep
if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 1
if i != 0 and getattr(tokenizer, "legacy", False) and IS_TOKENIZER_GREATER_THAN_0_14: round_len += 1 instruction_len += 1
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
cur_len += round_len target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print(f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f"(#turns={len(re_rounds)} ignored)")
return dict( input_ids=input_ids, labels=targets, )
def preprocess_plain( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer,) -> Dict: # add end signal and concatenate together conversations = [] for source in sources: assert len(source) == 2 assert DEFAULT_IMAGE_TOKEN in source[0]["value"] source[0]["value"] = DEFAULT_IMAGE_TOKEN conversation = source[0]["value"] + source[1]["value"] + conversation_lib.default_conversation.sep conversations.append(conversation) # tokenize conversations input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer)) target[:tokenized_len] = IGNORE_INDEX
return dict(input_ids=input_ids, labels=targets)
def preprocess(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False) -> Dict: """ Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. """ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: return preprocess_plain(sources, tokenizer) if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: return preprocess_llama_2(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version.startswith("v1"): return preprocess_v1(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version == "mpt": return preprocess_mpt(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version == "qwen": return preprocess_qwen(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version == "gemma": return preprocess_gemma(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version == "llama_v3": return preprocess_llama3(sources, tokenizer, has_image=has_image) # add end signal and concatenate together conversations = [] for source in sources: header = f"{conversation_lib.default_conversation.system}\n\n" conversation = _add_speaker_and_signal(header, source) conversations.append(conversation)
# tokenize conversations def get_tokenize_len(prompts): return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
if has_image: input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors="pt") for prompt in conversations] else: conversations_tokenized = _tokenize_fn(conversations, tokenizer) input_ids = conversations_tokenized["input_ids"]
targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): if has_image: tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) else: tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] speakers = [sentence["from"] for sentence in source] _mask_targets(target, tokenized_lens, speakers)
return dict(input_ids=input_ids, labels=targets)
def load_data(data_path): if "jsonl" in data_path: data_list = load_jsonl(data_path) else: data_list = load_json(data_path) return data_list
class DPODataset(Dataset): """Dataset for DPODataset fine-tuning."""
def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): super(DPODataset, self).__init__() # Handle multiple JSON files specified in the data_path self.list_data_dict = []
if "{" in data_path and "}" in data_path: base_path, file_pattern = re.match(r"^(.*)\{(.*)\}\.json$", data_path).groups() file_names = file_pattern.split(",") rank0_print(f"Loading {file_names} from {base_path}") data_args.dataset_paths = [] for file_name in file_names: data_args.dataset_paths.append(f"{base_path}{file_name}.json") full_path = f"{base_path}{file_name}.json" rank0_print(f"Loading {full_path}") cur_data_dict = load_data(full_path) rank0_print(f"Loaded {len(cur_data_dict)} samples from {full_path}") self.list_data_dict.extend(cur_data_dict) elif data_path.endswith(".yaml"): with open(data_path, "r") as file: yaml_data = yaml.safe_load(file) datasets = yaml_data.get("datasets") # file should be in the format of: # datasets: # - json_path: xxxx1.json # sampling_strategy: first:1000 # - json_path: xxxx2.json # sampling_strategy: end:3000 # - json_path: xxxx3.json # sampling_strategy: random:999 data_args.dataset_paths = [dataset.get("json_path") for dataset in datasets] for dataset in datasets: json_path = dataset.get("json_path") sampling_strategy = dataset.get("sampling_strategy", "all") sampling_number = None
rank0_print(f"Loading {json_path} with {sampling_strategy} sampling strategy") cur_data_dict = load_data(json_path)
if ":" in sampling_strategy: sampling_strategy, sampling_number = sampling_strategy.split(":") if "%" in sampling_number: sampling_number = math.ceil(int(sampling_number.split("%")[0]) * len(cur_data_dict) / 100) else: sampling_number = int(sampling_number)
# Apply the sampling strategy if sampling_strategy == "first" and sampling_number is not None: cur_data_dict = cur_data_dict[:sampling_number] elif sampling_strategy == "end" and sampling_number is not None: cur_data_dict = cur_data_dict[-sampling_number:] elif sampling_strategy == "random" and sampling_number is not None: random.shuffle(cur_data_dict) cur_data_dict = cur_data_dict[:sampling_number]
rank0_print(f"Loaded {len(cur_data_dict)} samples from {json_path}") self.list_data_dict.extend(cur_data_dict) else: data_args.dataset_paths = [data_path] rank0_print(f"Loading {data_path}") cur_data_dict = load_data(data_path) rank0_print(f"Loaded {len(cur_data_dict)} samples from {data_path}") self.list_data_dict.extend(cur_data_dict)
rank0_print("Formatting inputs...Skip in lazy mode") self.tokenizer = tokenizer self.data_args = data_args
def __len__(self): return len(self.list_data_dict)
@property def lengths(self): length_list = [] for sample in self.list_data_dict: # Calculate the length of the prompt, answer, chosen, and rejected text cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split()) # Add additional tokens if an image is present img_tokens = 128 if "image" in sample else 0 length_list.append(cur_len + img_tokens) return length_list
@property def modality_lengths(self): length_list = [] for sample in self.list_data_dict: # Calculate the length of the prompt, answer, chosen, and rejected text cur_len = len(sample["prompt"].split()) + len(sample["answer"].split()) + len(sample["chosen"].split()) + len(sample["rejected"].split()) # If the sample includes a video, the length is positive; otherwise, it is negative cur_len = cur_len if ("video" in sample or "image" in sample) else -cur_len length_list.append(cur_len) return length_list
def process_image(self, image_file): image_folder = self.data_args.image_folder processor = self.data_args.image_processor # print(f"\n\nInspecting the image path, folder = {image_folder}, image={image_file}\n\n") try: image = Image.open(os.path.join(image_folder, image_file)).convert("RGB") except Exception as exn: print(f"Failed to open image {image_file}. Exception:", exn) raise exn
image_size = image.size if self.data_args.image_aspect_ratio == "highres": image = process_highres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) elif self.data_args.image_aspect_ratio == "anyres" or "anyres" in self.data_args.image_aspect_ratio: image = process_anyres_image(image, self.data_args.image_processor, self.data_args.image_grid_pinpoints) elif self.data_args.image_aspect_ratio == "crop_split": image = process_highres_image_crop_split(image, self.data_args) elif self.data_args.image_aspect_ratio == "pad":
def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result
image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean)) image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] else: image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0] return image, image_size, "image"
def __getitem__(self, i) -> Dict[str, torch.Tensor]: # TODO: define number of retries somewhere else num_base_retries = 3 num_final_retries = 300
# try the current sample first for attempt_idx in range(num_base_retries): try: sample = self._get_item(i) return sample except Exception as e: # sleep 1s in case it is a cloud disk issue print(f"[Try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) time.sleep(1)
# try other samples, in case it is file corruption issue for attempt_idx in range(num_base_retries): try: next_index = min(i + 1, len(self.list_data_dict) - 1) # sample_idx = random.choice(range(len(self))) sample = self._get_item(next_index) return sample except Exception as e: # no need to sleep print(f"[Try other #{attempt_idx}] Failed to fetch sample {next_index}. Exception:", e) pass
# still fail, most likely to be path issue or cloud disk issue, retry the same sample for longer # for attempt_idx in range(num_final_retries): # try: # sample = self._get_item(i) # return sample # except Exception as e: # # sleep 1s in case it is a cloud disk issue # print(f"[Final try #{attempt_idx}] Failed to fetch sample {i}. Exception:", e) # time.sleep(1)
# Finally raise exception on failing. assert False, "Failed to fetch sample."
def _get_item(self, i) -> Dict[str, torch.Tensor]: sources = self.list_data_dict[i] if isinstance(i, int): sources = [sources] assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
suffix = None if "image" in sources[0]: image_file = self.list_data_dict[i]["image"] if type(image_file) is list: image = [self.process_image(f) for f in image_file] else: image = [self.process_image(image_file)] # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
elif "video" in sources[0]: # FIXME: This logic should be largely improved by Yuanhan. It's too messy now. video_file = self.list_data_dict[i]["video"] video_folder = self.data_args.video_folder video_file = os.path.join(video_folder, video_file) suffix = video_file.split(".")[-1] if not os.path.exists(video_file): print("File {} not exist!".format(video_file))
if suffix == "pkl": video_info = pickle.load(open(video_file, "rb")) image = torch.from_numpy(video_info["feats"][:, 1:]) input_prompt = video_info["inputs"].replace("...", "") # replace the default image token with multiple tokens input_prompt = input_prompt.replace(DEFAULT_IMAGE_TOKEN, DEFAULT_IMAGE_TOKEN * self.data_args.video_token) sources, query_prompt = preprocess_multimodal_movie(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, input_prompt) else: # using videoreader if "shareVideoGPTV" not in video_file and "liangke" not in video_file: vr = VideoReader(video_file, ctx=cpu(0)) total_frame_num = len(vr) avg_fps = round(vr.get_avg_fps() / self.data_args.video_fps) frame_idx = [i for i in range(0, total_frame_num, avg_fps)] if self.data_args.frames_upbound > 0: if len(frame_idx) > self.data_args.frames_upbound: uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.data_args.frames_upbound, dtype=int) frame_idx = uniform_sampled_frames.tolist() video = vr.get_batch(frame_idx).asnumpy() video = np.array(video) else: if "liangke" in video_file: video_file = self.list_data_dict[i]["video"] frame_files = [os.path.join(video_file, f) for f in os.listdir(video_file) if os.path.isfile(os.path.join(video_file, f))] frame_files.sort() # Ensure the frames are sorted if they are named sequentially
# TODO: Hard CODE: Determine the indices for uniformly sampling 10 frames num_frames_to_sample = 10
total_frames = len(frame_files)
sampled_indices = np.linspace(0, total_frames - 1, num_frames_to_sample, dtype=int)
# Read and store the sampled frames video = [] for idx in sampled_indices: frame_path = frame_files[idx] try: with Image.open(frame_path) as img: frame = img.convert("RGB") video.append(frame) except IOError: print(f"Failed to read frame at path: {frame_path}")
processor = self.data_args.image_processor image = processor.preprocess(video, return_tensors="pt")["pixel_values"] image = [(image, video[0].size, "video")] # sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args)
else: sources = copy.deepcopy([e["conversations"] for e in sources])
has_image = ("image" in self.list_data_dict[i]) or ("video" in self.list_data_dict[i]) # data_dict = preprocess(sources, self.tokenizer, has_image=has_image) data_dict = copy.deepcopy(self.list_data_dict[i]) # inplace modification following
if "prompt" in data_dict: prompt = data_dict["prompt"] prompt = prompt.replace("<image>", "").strip() prompt = "<image>\n" + prompt data_dict["prompt"] = prompt else: prompt = None
if suffix == "pkl": prompt = [query_prompt]
# image exist in the data if "image" in self.list_data_dict[i]: data_dict["image"] = image elif "video" in self.list_data_dict[i]: data_dict["image"] = image elif self.data_args.is_multimodal: # image does not exist in the data, but the model is multimodal crop_size = self.data_args.image_processor.crop_size data_dict["image"] = [ (torch.zeros(1, 3, crop_size["height"], crop_size["width"]), (crop_size["width"], crop_size["height"]), "text"), ] # prompt exist in the data data_dict["has_image"] = has_image return data_dict
@dataclassclass DPODataCollator(DPODataCollatorWithPadding): """Collate examples for DPO fine-tuning."""
# tokenizer: transformers.PreTrainedTokenizer
def collate(self, batch): # first, pad everything to the same length # input_ids, labels = tuple([instance[key] for instance in instances] # for key in ("input_ids", "labels")) # input_ids = torch.nn.utils.rnn.pad_sequence( # input_ids, # batch_first=True, # padding_value=self.tokenizer.pad_token_id) # labels = torch.nn.utils.rnn.pad_sequence(labels, # batch_first=True, # padding_value=IGNORE_INDEX) # input_ids = input_ids[:, :self.tokenizer.model_max_length] # labels = labels[:, :self.tokenizer.model_max_length] # batch = dict( # input_ids=input_ids, # labels=labels, # attention_mask=input_ids.ne(self.tokenizer.pad_token_id), # ) padded_batch = {} for k in batch[0].keys(): if k.endswith("_input_ids") or k.endswith("_attention_mask") or k.endswith("_labels"): # if "prompt" in k: # to_pad = [torch.LongTensor(ex[k][::-1]) for ex in batch] # else: to_pad = [torch.LongTensor(ex[k]) for ex in batch] if k.endswith("_input_ids"): padding_value = self.tokenizer.pad_token_id elif k.endswith("_labels"): padding_value = self.label_pad_token_id else: continue # elif k.endswith("_attention_mask"): # padding_value = self.padding_value # else: # raise ValueError(f"Unexpected key in batch '{k}'")
padded_batch[k] = torch.nn.utils.rnn.pad_sequence(to_pad, batch_first=True, padding_value=padding_value) # for the prompt, flip back so padding is on left side # if "prompt" in k: # padded_batch[k] = padded_batch[k].flip(dims=[1]) else: padded_batch[k] = [ex[k] for ex in batch] for k in ["chosen_input_ids", "rejected_input_ids"]: attn_k = k.replace("input_ids", "attention_mask") padded_batch[attn_k] = padded_batch[k].ne(self.tokenizer.pad_token_id) return padded_batch
def tokenize_batch_element(self, prompt: str, chosen: str, rejected: str, has_image: bool = True) -> Dict: """Tokenize a single batch element.
At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the chosen/rejected.
We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length of the prompt and the chosen/rejected response, with label_pad_token_id for the prompt tokens. """ # import pdb; pdb.set_trace() batch = {}
chosen_sources = make_conv(prompt, chosen) rejected_sources = make_conv(prompt, rejected) chosen_data_dict = preprocess([chosen_sources], self.tokenizer, has_image=has_image) # chosen_data_dict['attention_mask'] = chosen_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
rejected_data_dict = preprocess([rejected_sources], self.tokenizer, has_image=has_image) # rejected_data_dict['attention_mask'] = rejected_data_dict["input_ids"].ne(self.tokenizer.pad_token_id)
chosen_data_dict = {k: v[0] for k, v in chosen_data_dict.items()} rejected_data_dict = {k: v[0] for k, v in rejected_data_dict.items()}
for k, toks in { "chosen": chosen_data_dict, "rejected": rejected_data_dict, }.items(): for type_key, tokens in toks.items(): if type_key == "token_type_ids": continue batch[f"{k}_{type_key}"] = tokens return batch
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
tokenized_batch = [] Xs, keys = [], [] for feature in features: prompt = feature["prompt"] chosen = feature["chosen"] rejected = feature["rejected"] has_image = feature["has_image"] # Xs.append(feature[has_X]) # keys.append(has_X)
batch_element = self.tokenize_batch_element(prompt, chosen, rejected, has_image=has_image) tokenized_batch.append(batch_element)
# return collated batch padded_batch = self.collate(tokenized_batch) # import pdb;pdb.set_trace() if "image" in features[0]: # instances[1]['image'][0][0].shape # torch.Size([5, 3, 224, 224]) images = [instance["image"] for instance in features]
padded_batch["image_sizes"] = [im[1] for im_list in images for im in im_list] padded_batch["modalities"] = [im[2] for im_list in images for im in im_list] images = [im[0] for im_list in images for im in im_list] # import pdb;pdb.set_trace()
padded_batch["images"] = images # padded_batch["images"] =[padded_batch["modalities"], images]
return padded_batch
def make_dpo_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = DPODataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) return train_dataset
def get_model(model_args, training_args, bnb_model_from_pretrained_args): assert training_args.attn_implementation if training_args.attn_implementation == "sdpa" and torch.__version__ < "2.1.2": raise ValueError("The 'sdpa' attention implementation requires torch version 2.1.2 or higher.")
######################### Overwrite config ######################### customized_kwargs = dict() customized_kwargs.update(bnb_model_from_pretrained_args) overwrite_config = {} cfg_pretrained = None if "qwen" in model_args.model_name_or_path.lower(): cfg_pretrained = LlavaQwenConfig.from_pretrained(model_args.model_name_or_path) elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): cfg_pretrained = LlavaMistralConfig.from_pretrained(model_args.model_name_or_path) elif ( "wizardlm-2" in model_args.model_name_or_path.lower() or "vicuna" in model_args.model_name_or_path.lower() or "llama" in model_args.model_name_or_path.lower() or "yi" in model_args.model_name_or_path.lower() or "nous-hermes" in model_args.model_name_or_path.lower() and "wizard-2" in model_args.model_name_or_path.lower() ): cfg_pretrained = LlavaConfig.from_pretrained(model_args.model_name_or_path) else: cfg_pretrained = AutoConfig.from_pretrained(model_args.model_name_or_path)
if model_args.rope_scaling_factor is not None and model_args.rope_scaling_type is not None and cfg_pretrained is not None: overwrite_config["rope_scaling"] = { "factor": model_args.rope_scaling_factor, "type": model_args.rope_scaling_type, } if training_args.model_max_length is None: training_args.model_max_length = cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor overwrite_config["max_sequence_length"] = training_args.model_max_length assert training_args.model_max_length == int(cfg_pretrained.max_position_embeddings * model_args.rope_scaling_factor), print( f"model_max_length: {training_args.model_max_length}, max_position_embeddings: {cfg_pretrained.max_position_embeddings}, rope_scaling_factor: {model_args.rope_scaling_factor}" ) # overwrite_config["max_sequence_length"] = model_args.max_sequence_length # overwrite_config["tokenizer_model_max_length"] = model_args.tokenizer_model_max_length
if model_args.mm_spatial_pool_stride is not None and model_args.mm_spatial_pool_out_channels is not None and model_args.mm_spatial_pool_mode is not None and model_args.mm_resampler_type is not None and cfg_pretrained is not None: overwrite_config["mm_resampler_type"] = model_args.mm_resampler_type overwrite_config["mm_spatial_pool_stride"] = model_args.mm_spatial_pool_stride overwrite_config["mm_spatial_pool_out_channels"] = model_args.mm_spatial_pool_out_channels overwrite_config["mm_spatial_pool_mode"] = model_args.mm_spatial_pool_mode
if overwrite_config: rank0_print(f"Overwriting config with {overwrite_config}") for k, v in overwrite_config.items(): setattr(cfg_pretrained, k, v)
customized_kwargs["config"] = cfg_pretrained
######################### Finish Overwrite ###########################
ref_model = None if model_args.model_class_name is not None: actual_model_class_name = f"{model_args.model_class_name}ForCausalLM" model_class = getattr(transformers, actual_model_class_name) rank0_print(f"Using model class {model_class} from {model_args.model_class_name}") model = model_class.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, ) elif model_args.vision_tower is not None: if "mixtral" in model_args.model_name_or_path.lower(): model = LlavaMixtralForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, ) from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock]) elif "mistral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): model = LlavaMistralForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, ) elif ( "wizardlm-2" in model_args.model_name_or_path.lower() or "vicuna" in model_args.model_name_or_path.lower() or "llama" in model_args.model_name_or_path.lower() or "yi" in model_args.model_name_or_path.lower() or "nous-hermes" in model_args.model_name_or_path.lower() and "wizard-2" in model_args.model_name_or_path.lower() ): model = LlavaLlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, )
if "zero3" in training_args.deepspeed: rank0_print("#### Initialize reference model #####") ref_model = LlavaLlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, )
elif "qwen" in model_args.model_name_or_path.lower() or "quyen" in model_args.model_name_or_path.lower(): if "moe" in model_args.model_name_or_path.lower(): model = LlavaQwenMoeForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, ) from transformers.models.qwen2_moe.modeling_qwen2_moe import Qwen2MoeSparseMoeBlock
deepspeed.utils.set_z3_leaf_modules(model, [Qwen2MoeSparseMoeBlock]) else: model = LlavaQwenForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, )
if "zero3" in training_args.deepspeed: rank0_print("#### Initialize reference model #####") ref_model = LlavaQwenForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, )
elif "gemma" in model_args.model_name_or_path.lower(): model = LlavaGemmaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), low_cpu_mem_usage=False, **customized_kwargs, ) else: raise ValueError(f"Unknown model class {model_args}") else: model = transformers.LlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, attn_implementation=training_args.attn_implementation, torch_dtype=(torch.bfloat16 if training_args.bf16 else None), **customized_kwargs ) return model, ref_model
def train(attn_implementation=None): global local_rank
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses()
if training_args.verbose_logging: rank0_print(f"Inspecting experiment hyperparameters:\n") rank0_print(f"model_args = {vars(model_args)}\n\n") rank0_print(f"data_args = {vars(data_args)}\n\n") rank0_print(f"training_args = {vars(training_args)}\n\n") # rank0_print(f"evaluation_args = {vars(evaluation_args)}\n\n")
local_rank = training_args.local_rank compute_dtype = torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)
bnb_model_from_pretrained_args = {} if training_args.bits in [4, 8]: from transformers import BitsAndBytesConfig
bnb_model_from_pretrained_args.update( dict( device_map={"": training_args.device}, load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, quantization_config=BitsAndBytesConfig( load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, llm_int8_threshold=6.0, llm_int8_has_fp16_weight=False, bnb_4bit_compute_dtype=compute_dtype, bnb_4bit_use_double_quant=training_args.double_quant, bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'} ), ) )
model, ref_model = get_model(model_args, training_args, bnb_model_from_pretrained_args) model.config.use_cache = False
if model_args.freeze_backbone: model.model.requires_grad_(False)
if training_args.bits in [4, 8]: from peft import prepare_model_for_kbit_training
model.config.torch_dtype = torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32) model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
if training_args.gradient_checkpointing: if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() if ref_model is not None: ref_model.enable_input_require_grads() else:
def make_inputs_require_grad(module, input, output): output.requires_grad_(True)
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
if ref_model is not None: ref_model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
if training_args.lora_enable: from peft import LoraConfig, get_peft_model
lora_config = LoraConfig( r=training_args.lora_r, lora_alpha=training_args.lora_alpha, target_modules=find_all_linear_names(model), lora_dropout=training_args.lora_dropout, bias=training_args.lora_bias, task_type="CAUSAL_LM", ) if training_args.bits == 16: if training_args.bf16: model.to(torch.bfloat16) if training_args.fp16: model.to(torch.float16) rank0_print("Adding LoRA adapters...") model = get_peft_model(model, lora_config)
if "mpt" in model_args.model_name_or_path: tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right") elif "mistral" in model_args.model_name_or_path.lower() or "mixtral" in model_args.model_name_or_path.lower() or "zephyr" in model_args.model_name_or_path.lower(): tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="left") elif "qwen" in model_args.model_name_or_path.lower(): tokenizer = transformers.AutoTokenizer.from_pretrained(model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right") else: # for all other models tokenizer = transformers.AutoTokenizer.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right", use_fast=False, )
rank0_print(f"Prompt version: {model_args.version}") if model_args.version == "v0": if tokenizer.pad_token is None: smart_tokenizer_and_embedding_resize( special_tokens_dict=dict(pad_token="[PAD]"), tokenizer=tokenizer, model=model, ) elif model_args.version == "v0.5": tokenizer.pad_token = tokenizer.unk_token else: if tokenizer.unk_token is not None: tokenizer.pad_token = tokenizer.unk_token if model_args.version in conversation_lib.conv_templates: conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] else: conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
if model_args.vision_tower is not None: model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
vision_tower = model.get_vision_tower() vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
data_args.image_processor = vision_tower.image_processor data_args.is_multimodal = True
model.config.image_aspect_ratio = data_args.image_aspect_ratio if data_args.image_grid_pinpoints is not None: # for input like "(1x1)...(3x3)", convert to [(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)] if "x" in data_args.image_grid_pinpoints and "..." in data_args.image_grid_pinpoints: vis_encoder_size = data_args.image_processor.size[0] matches = re.findall(r"\((\d+)x(\d+)\)", data_args.image_grid_pinpoints) range_start = tuple(map(int, matches[0])) range_end = tuple(map(int, matches[-1])) grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)] grid_pinpoints = [[dim * vis_encoder_size for dim in pair] for pair in grid_pinpoints] data_args.image_grid_pinpoints = grid_pinpoints elif "x" in data_args.image_grid_pinpoints: vis_encoder_size = data_args.image_processor.size[0] assert vis_encoder_size in [224, 336, 384, 448, 512], "vis_encoder_size should be in [224, 336, 384, 448, 512]" grid_pinpoints = data_args.image_grid_pinpoints.replace(" ", "").replace("x", ",")[1:-1].split("),(") data_args.image_grid_pinpoints = [[int(x) * vis_encoder_size for x in item.split(",")] for item in grid_pinpoints] else: data_args.image_grid_pinpoints = ast.literal_eval(data_args.image_grid_pinpoints) # for backward compatibility model.config.image_grid_pinpoints = data_args.image_grid_pinpoints model.config.image_crop_resolution = data_args.image_crop_resolution model.config.image_split_resolution = data_args.image_split_resolution model.config.tokenizer_padding_side = tokenizer.padding_side model.config.tokenizer_model_max_length = tokenizer.model_max_length
### Deciding train which part of the model if model_args.mm_tunable_parts is None: # traditional way of deciding which part to train model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter model.config.tune_mm_vision_resampler = training_args.tune_mm_vision_resampler = model_args.tune_mm_vision_resampler if model_args.tune_mm_mlp_adapter or model_args.tune_mm_vision_resampler: model.requires_grad_(False) if model_args.tune_mm_mlp_adapter: for p in model.get_model().mm_projector.parameters(): p.requires_grad = True if model_args.tune_mm_vision_resampler: for p in model.get_model().vision_resampler.parameters(): p.requires_grad = True
model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter if training_args.freeze_mm_mlp_adapter: for p in model.get_model().mm_projector.parameters(): p.requires_grad = False
model.config.freeze_mm_vision_resampler = training_args.freeze_mm_vision_resampler if training_args.freeze_mm_vision_resampler: for p in model.get_model().vision_resampler.parameters(): p.requires_grad = False
model.config.unfreeze_mm_vision_tower = model_args.unfreeze_mm_vision_tower if model_args.unfreeze_mm_vision_tower: vision_tower.requires_grad_(True) else: vision_tower.requires_grad_(False)
else: rank0_print(f"Using mm_tunable_parts: {model_args.mm_tunable_parts}") model.config.mm_tunable_parts = training_args.mm_tunable_parts = model_args.mm_tunable_parts # Set the entire model to not require gradients by default model.requires_grad_(False) vision_tower.requires_grad_(False) model.get_model().mm_projector.requires_grad_(False) model.get_model().vision_resampler.requires_grad_(False) # Parse the mm_tunable_parts to decide which parts to unfreeze tunable_parts = model_args.mm_tunable_parts.split(",") if "mm_mlp_adapter" in tunable_parts: for p in model.get_model().mm_projector.parameters(): p.requires_grad = True if "mm_vision_resampler" in tunable_parts: for p in model.get_model().vision_resampler.parameters(): p.requires_grad = True if "mm_vision_tower" in tunable_parts: for name, param in model.named_parameters(): if "vision_tower" in name: param.requires_grad_(True) if "mm_language_model" in tunable_parts: for name, param in model.named_parameters(): if "vision_tower" not in name and "mm_projector" not in name and "vision_resampler" not in name: param.requires_grad_(True)
total_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters()) trainable_params = sum(p.ds_numel if hasattr(p, "ds_numel") else p.numel() for p in model.parameters() if p.requires_grad) rank0_print(f"Total parameters: ~{total_params/1e6:.2f} MB)") rank0_print(f"Trainable parameters: ~{trainable_params/1e6:.2f} MB)") if training_args.bits in [4, 8]: model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end model.config.mm_projector_lr = training_args.mm_projector_lr model.config.mm_vision_tower_lr = training_args.mm_vision_tower_lr training_args.use_im_start_end = model_args.mm_use_im_start_end model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
if ref_model is not None: ref_model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp) ref_vision_tower = ref_model.get_vision_tower() ref_vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) ref_model.config.image_aspect_ratio = data_args.image_aspect_ratio ref_model.config.image_grid_pinpoints = data_args.image_grid_pinpoints ref_model.config.image_crop_resolution = data_args.image_crop_resolution ref_model.config.image_split_resolution = data_args.image_split_resolution ref_model.config.tokenizer_padding_side = tokenizer.padding_side ref_model.config.tokenizer_model_max_length = tokenizer.model_max_length ref_model.config.mm_use_im_start_end = data_args.mm_use_im_start_end ref_model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token ref_model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer) parameter_names = [n for n, _ in ref_model.named_parameters()] for param_name in parameter_names: param = ref_model.get_parameter(param_name) param.requires_grad = False ref_model.eval()
if training_args.bits in [4, 8]: from peft.tuners.lora import LoraLayer
for name, module in model.named_modules(): if isinstance(module, LoraLayer): if training_args.bf16: module = module.to(torch.bfloat16) if "norm" in name: module = module.to(torch.float32) if "lm_head" in name or "embed_tokens" in name: if hasattr(module, "weight"): if training_args.bf16 and module.weight.dtype == torch.float32: module = module.to(torch.bfloat16)
train_dataset = make_dpo_data_module(tokenizer=tokenizer, data_args=data_args) data_collator = DPODataCollator( tokenizer, label_pad_token_id=IGNORE_INDEX, pad_token_id=tokenizer.pad_token_id, )
trainer = LLaVADPOTrainer( model, ref_model, args=training_args, dpo_alpha=training_args.dpo_alpha, beta=training_args.beta, gamma=training_args.gamma, train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator, tokenizer=tokenizer, max_length=training_args.model_max_length, generate_during_eval=False, # training_args.generate_during_eval, precompute_ref_log_probs=training_args.precompute_ref_log_probs, )
if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): trainer.train(resume_from_checkpoint=True) else: trainer.train() trainer.save_state()
model.config.use_cache = True
if training_args.lora_enable: state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias) non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters()) if training_args.local_rank == 0 or training_args.local_rank == -1: if hasattr(model, "config"): model.config.save_pretrained(training_args.output_dir) if hasattr(model, "generation_config"): model.generation_config.save_pretrained(training_args.output_dir) model.save_pretrained(training_args.output_dir, state_dict=state_dict) torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, "non_lora_trainables.bin")) else: safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
rank0_print(f"Model saved to {training_args.output_dir}")
if __name__ == "__main__": train()1234567891011docutils==0.18.1modelindexmyst-parser-e git+https://github.com/open-compass/pytorch_sphinx_theme.git#egg=pytorch_sphinx_themesphinx==6.1.3sphinx-copybuttonsphinx-designsphinx-notfound-pagesphinx-tabssphinxcontrib-jquerytabulate123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354from .image_base import ImageBaseDatasetimport randomfrom collections import Counterimport osimport reimport tempfilefrom ..smp import *from ..smp.file import get_intermediate_file_path
def get_multi_choice_prediction(response, all_choices, index2ans): for char in [',', '.', '!', '?', ';', ':', "'"]: response = response.strip(char) response = " " + response + " " # add space to avoid partial match
candidates = []
for choice in all_choices: # (A) (B) (C) (D) # Add the choice to candidates each time it appears in the response candidates.extend([choice for _ in range(response.count(f'({choice})'))])
if len(candidates) == 0: for choice in all_choices: # A B C D # Similarly, add the choice for each occurrence candidates.extend([choice for _ in range(response.count(f'{choice}'))])
if len(candidates) == 0 and len(response.split()) >= 1: for index, ans in index2ans.items(): # Add index for each occurrence of ans in response candidates.extend([index for _ in range(response.count(ans))])
# if all above doesn't get candidates, check if the content is larger than 5 tokens and try to parse the example if len(candidates) == 0 and len(response.split()) >= 1: for index, ans in index2ans.items(): if ans in response: candidates.append(index) # index_ans = False # it's content ans.
if len(candidates) == 0: # still not get answer, randomly choose one. return random.choice(all_choices) # return '' else: # Count the occurrence of each candidate candidate_counts = Counter(candidates)
# Select the most frequent candidates max_count = max(candidate_counts.values()) most_frequent_candidates = [c for c in all_choices if candidate_counts.get(c, 0) == max_count]
# Combine the most frequent candidates in ABCD order return ''.join(most_frequent_candidates)
def extract_numbers(string): # Pattern for numbers with Chinese commas pattern_commas = r'-?\d{1,3}(?:,\d{3})+' # Pattern for scientific notation pattern_scientific = r'-?\d+(?:\.\d+)?[eE][+-]?\d+' # Pattern for simple numbers without Chinese commas pattern_simple = r'-?(?:\d+\.\d+|\.\d+|\d+)(?![eE][+-]?\d+)(?!,\d)'
# Extract numbers with Chinese commas numbers_with_commas = re.findall(pattern_commas, string) # Extract numbers in scientific notation numbers_scientific = re.findall(pattern_scientific, string) # Extract simple numbers without Chinese commas numbers_simple = re.findall(pattern_simple, string)
# Combine all extracted numbers all_numbers = numbers_with_commas + numbers_scientific + numbers_simple return all_numbers
def check_is_number(string): try: float(string.replace(',', '')) return True except ValueError: # check if there's comma inside return False
def count_letters(string): return sum(c.isalpha() and 'a' <= c <= 'z' or 'A' <= c <= 'Z' for c in string)
def normalize_str(string, answer): # check if characters in the string
# if number, numerize it. if string is None: return [string] string = string.strip()
is_number = check_is_number(string)
if is_number: string = string.replace(',', '') string = float(string) # leave 2 decimal string = round(string, 2) return [string] else: # it's likely to be a string if len(string) > len(answer) + 20 or count_letters(string) > count_letters(answer) + 2: return [] return [string]
def get_fill_blank_prediction(response, answer): """get the prediction from the generated response, return a list of predicted strings or numbers"""
def get_key_subresponses(response): response = response.strip("。").strip() sub_responses = re.split(r'。|\n', response) indicators_of_keys = ['是', '为', '所以', '等于', '方案', '选择', '正确答案', '因此', '最后', '答案', '结果'] key_responses = [] for index, resp in enumerate(sub_responses): # if last one, accept it's an equation (the entire response can be just one sentence with equation) if index == len(sub_responses) - 1: indicators_of_keys.extend(['=']) shortest_key_response = None # the shortest response that may contain the answer (tail part of the response) for indicator in indicators_of_keys: if indicator in resp: if not shortest_key_response: shortest_key_response = resp.split(indicator)[-1].strip() else: if len(resp.split(indicator)[-1].strip()) < len(shortest_key_response): shortest_key_response = resp.split(indicator)[-1].strip()
if shortest_key_response: # and it's not trivial if shortest_key_response.strip() not in [":", ",", ".", "!", "?", ";", ":", "'"]: key_responses.append(shortest_key_response) if len(key_responses) == 0: # did not found any return [response] return key_responses
key_responses = get_key_subresponses(response)
pred_list = key_responses.copy() # keep the original string response for resp in key_responses: pred_list.extend(extract_numbers(resp))
tmp_pred_list = [] for i in range(len(pred_list)): tmp_pred_list.extend(normalize_str(pred_list[i], answer)) pred_list = tmp_pred_list
# remove duplicates pred_list = list(set(pred_list))
return pred_list
def get_TF_prediction(response): """get the prediction from the generated response, return a list of predicted strings or numbers"""
def get_key_subresponses(response): response = response.strip("。").strip() sub_responses = re.split(r'。|\n', response) indicators_of_keys = ['是', '为', '所以', '判断', '陈述', '说法', '表达', '答案', '结果'] key_responses = [] for index, resp in enumerate(sub_responses): shortest_key_response = None # the shortest response that may contain the answer (tail part of the response) for indicator in indicators_of_keys: if indicator in resp: if not shortest_key_response: shortest_key_response = resp.split(indicator)[-1].strip() else: if len(resp.split(indicator)[-1].strip()) < len(shortest_key_response): shortest_key_response = resp.split(indicator)[-1].strip()
if shortest_key_response: # and it's not trivial if shortest_key_response.strip() not in [":", ",", ".", "!", "?", ";", ":", "'"]: key_responses.append(shortest_key_response) if len(key_responses) == 0: # did not found any return [response] return key_responses
key_responses = get_key_subresponses(response)
pred_list = key_responses.copy() # keep the original string response # remove duplicates pred_list = list(set(pred_list))
return pred_list
class CMMMU(ImageBaseDataset): TYPE = 'VQA'
DATASET_URL = { 'CMMMU_VAL': 'https://opencompass.openxlab.space/utils/VLMEval/CMMMU_VAL.tsv' }
DATASET_MD5 = { 'CMMMU_VAL': 'b4727e2fce2415bf646379e60c11a726' }
def dump_image(self, line): os.makedirs(self.img_root, exist_ok=True)
tgt_path_z = [] if isinstance(line['image'], list): for i in range(len(line['image'])): tgt_path = osp.join(self.img_root, f"{line['index']}--{i + 1}.jpg") if not read_ok(tgt_path): decode_base64_to_image_file(line['image'][i], tgt_path) tgt_path_z.append(tgt_path) else: tgt_path = osp.join(self.img_root, f"{line['index']}.jpg") if not read_ok(tgt_path): decode_base64_to_image_file(line['image'], tgt_path) tgt_path_z.append(tgt_path) return tgt_path_z
@classmethod def evaluate(self, eval_file, **judge_kwargs):
result_file = get_intermediate_file_path(eval_file, '_acc', 'csv')
if not osp.exists(result_file): data = load(eval_file) assert 'answer' in data and 'prediction' in data data['prediction'] = [str(x) for x in data['prediction']] data['answer'] = [str(x) for x in data['answer']]
correct_count = 0 correct_category = { '技术与工程': [0, 0], '科学': [0, 0], '健康与医学': [0, 0], '商业': [0, 0], '艺术与设计': [0, 0], '人文社会科学': [0, 0], }
for i in tqdm(data.iterrows()): line = i[1] correct_category[line['category']][0] += 1
# Options if line['type'] == '选择': index2ans = { 'A': line['option1'], 'B': line['option2'], 'C': line['option3'], 'D': line['option4'] } fact_option = get_multi_choice_prediction(line['prediction'], ['A', 'B', 'C', 'D'], index2ans) if fact_option == line['answer']: correct_count += 1 correct_category[line['category']][1] += 1
# Binary elif line['type'] == '判断': positive_keywords = ['正确', '对', '准确', '肯定', '对的'] negative_keywords = ['不对', '错误', '不正确', '不准确', '不合适', '否定', '错的', '错'] ambiguous_keywords = ['对错', '是否正确', '否正确', '或者', '是否', '正确性', '对不']
def judge_similarity(pred_list, positive_keywords, negative_keywords): positive_count = 0 negative_count = 0
for pred in pred_list: if any(pos_word in pred for pos_word in positive_keywords): positive_count += 1 elif any(neg_word in pred for neg_word in negative_keywords): negative_count += 1
if positive_count > negative_count: return "对" elif negative_count > positive_count: return "错" else: return random.choice(['对', '错'])
answer = get_TF_prediction(line['prediction']) answer = [word for word in answer if not any(ambiguous in word for ambiguous in ambiguous_keywords)] fact_answer = judge_similarity(answer, positive_keywords, negative_keywords) if fact_answer == line['answer']: correct_count += 1 correct_category[line['category']][1] += 1
# Fill the Blank else: norm_answers = normalize_str(line['answer'], line['answer']) predicted_answer = get_fill_blank_prediction(line['prediction'], line['answer'])
for pred in predicted_answer: # already normalized if isinstance(pred, str): # if it's a string, then find if ans in the pred_i for norm_ans in norm_answers: # only see if the string answer in the string pred # print(norm_ans, pred) if isinstance(norm_ans, str) and norm_ans in pred: correct_count += 1 correct_category[line['category']][1] += 1 else: # it's a number if pred in norm_answers: correct_count += 1 correct_category[line['category']][1] += 1
accuracyz = {} accuracyz['总准确率'] = correct_count / len(data) for i in correct_category.keys(): accuracyz[i] = correct_category[i][1] / correct_category[i][0]
accuracyz = d2df(accuracyz) accuracyz.round(10) dump(accuracyz, result_file)
result = pd.read_csv(result_file) return result
def build_prompt(self, line): if line['type'] == '选择': tgt_path = self.dump_image(line) question = line['question'] options_prompt = 'Options:\n'
for i in [['A', '1'], ['B', '2'], ['C', '3'], ['D', '4']]: options_prompt += i[0] + '. ' + line['option' + i[1]] + '\n'
prompt = (f'问题: {question}\n' + options_prompt + '请回答上述多项选择题,并选出正确选项。这些题目可能包括单选和多选题型。如果所提供的信息不足以确定一个明确的答案,那么请根据可用的数据和你的判断来选择最可能正确的选项。')
msgs = [] if isinstance(tgt_path, list): msgs.extend([dict(type='image', value=p) for p in tgt_path]) else: msgs = [dict(type='image', value=tgt_path)] msgs.append(dict(type='text', value=prompt))
return msgs
elif line['type'] == '判断': msgs = super().build_prompt(line) assert msgs[-1]['type'] == 'text' msgs[-1]['value'] += '\n请回答上述判断题,并根据题目描述和所给的信息来判断问题中陈述的对错。如果信息不完整或不足以作出绝对判断,请运用你的逻辑推理和现有信息来做出最可能的判断。' return msgs
else: msgs = super().build_prompt(line) assert msgs[-1]['type'] == 'text' msgs[-1]['value'] += '\n请回答上述填空题,并根据题目的要求和所提供的信息来给出最恰当的答案。如果信息不足以确切回答,那么请依据现有的数据和你的推理能力来填写最合理的答案。' return msgs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741# flake8: noqafrom .image_base import ImageBaseDatasetimport numpy as npimport pandas as pdfrom ..smp import *from ..smp.file import get_intermediate_file_pathfrom .utils import build_judge, DEBUG_MESSAGEfrom ..utils import track_progress_richimport re
prompt_dict = {}prompt_dict['LiveMMBench_Creation'] = { # Subjective Judge [GPT-4o reference] 'subjective':"""Please act as an impartial judge and evaluate the quality of two responses provided by AI assistants to the user prompt.
Your task is to carefully assess two responses based on provided instructions and evaluation criteria. After evaluating both responses, determine which response features better quality and better meets the criteria. If both responses are similar or nearly identical in quality, you should indicate a tie. Avoid position bias toward the first or second response.
Suggested Steps for Evaluation:1. Review both responses independently and then carefully compare their strengths and weaknesses. A good response should feature good language quality, follow the user instruction and meet as many criteria as possible.2. After completing the first evaluation, swap the positions of response A and B and repeat Step 1 and get the 2nd evaluation outcome. This helps to mitigate the potential position bias.3. After completing both evaluations (in the original and reversed order), combine your analysis and provide a final conclusion based on the overall assessment. If both responses are relatively similar, or the differences are minimal and hard to distinguish, your conclusion should indicate a tie ([[A=B]]).
Your **conclusion** should be one of the following options (A, B are of the original order):1. [[A>>B]]: Response A is clearly better than Response B.2. [[A>B]]: Response A is slightly better than Response B.3. [[A=B]]: Response A is nearly identical to Response B.4. [[B>A]]: Response B is slightly better than Response A.5. [[B>>A]]: Response B is clearly better than Response A.
User Instruction:\n[INSTRUCTIONS]\n{instructions}\n[END INSTRUCTIONS]\n\nRepsonse A:\n[RESPONSE A]\n{reference_answer_by_gpt4o}\n[END RESPONSE A]\n\nResponse B:\n[RESPONSE B]\n{prediction}\n[END RESPONSE B]\n\nEvaluation Criteria:\n[CRITERIA]\n{criteria}\n[END CRITERIA]\n\n
Your output should include:1. Conclusion: Your final conclusion based on the overall assessment.2. Reasoning: Your reasoning process and analysis of the two responses.
Your output should follow the following format (CONCLUSION should be one of the five options: A>>B, A>B, A=B, B>A, B>>A):
Final Conclusion: [[CONCLUSION]]Reasoning Process: [REASONING]\n""",
# Criteria Alignment w/o GT 'objective_without_gt':"""Please act as an impartial judge and evaluate the **Criteria Alignment** of the two responses provided by AI assistants to the user prompt. The responses were generated based on the provided instructions and visual input from images.
Suggested Steps for Evaluation:1. Evaluate **Criteria Alignment** of both responses based on the criteria. • If a criterion consist of **X aspects**, each aspect is worth **10 / X points**. • For each aspect, there may be multiple sub-criteria. If there are **Y sub-criteria for the aspect**, each sub-criterion worths **10 / (X * Y) points**.2. Assign a total score out of 10 for each response.
User Instruction:\n[INSTRUCTIONS]\n{instructions}\n[END INSTRUCTIONS]\n\nRepsonse A:\n[RESPONSE A]\n{reference_answer_by_gpt4o}\n[END RESPONSE A]\n\nResponse B:\n[RESPONSE B]\n{prediction}\n[END RESPONSE B]\n\nCriteria:\n[CRITERIA]\n{criteria}\n[END CRITERIA]\n\n
Your output should evaluate alignment scores of each response and end with a conclusion in the following format (The full score is 10. X, Y are alignment scores for Response A and B):
Response A Alignment Score: X/10Response B Alignment Score: Y/10\n""",
# Criteria Alignment w. GT 'objective_with_gt':"""Please act as an impartial judge and evaluate the **Criteria Alignment** of the two responses provided by AI assistants to the user prompt. The responses were generated based on the provided instructions and visual input from images. There is also a ground truth corresponding to the instructions provided for reference.Take this context into account when making your judgment.
Steps for Evaluation:1. Evaluate **Criteria Alignment** of both responses based on the criteria and the ground truth. • If a criterion consist of **X aspects**, each aspect is worth **10 / X points**. • For each aspect, there may be multiple sub-criteria. If there are **Y sub-criteria for the aspect**, each sub-criterion worths **10 / (X * Y) points**.2. Assign a total score out of 10 for each response.
User Instruction:\n[INSTRUCTIONS]\n{instructions}\n[END INSTRUCTIONS]\n\nGround Truth:\n[GROUND TRUTH]\n{groundtruth}\n[END GROUND TRUTH]\n\nRepsonse A:\n[RESPONSE A]\n{reference_answer_by_gpt4o}\n[END RESPONSE A]\n\nResponse B:\n[RESPONSE B]\n{prediction}\n[END RESPONSE B]\n\nCriteria:\n[CRITERIA]\n{criteria}\n[END CRITERIA]\n\n
Your output should evaluate alignment scores of each response and end with a conclusion in the following format (The full score is 10. X, Y are alignment scores for Response A and B):
Response A Alignment Score: X/10Response B Alignment Score: Y/10\n""",}
prompt_dict['Creation_MMBench'] = { # Subjective Judge [GPT-4o reference, with image] 'subjective':"""Please act as an impartial judge and evaluate the quality of the responses provided by two AI assistants to the user prompt below, considering both the provided criteria and the image.
Your task is to carefully assess each response based on how well it meets the evaluation criteria, incorporating the visual context from the image. The criteria should be the primary basis for your judgment, with the image serving to complement and inform your analysis.
Steps for Evaluation: 1. Review Both Responses Independently: Carefully analyze Assistant A’s and Assistant B’s responses with the criteria and the image. Do not assume any response is better just because it is listed first. Each response should be independently assessed based on the criteria and aided by images to help understand the context.
2. Compare the Strengths and Weaknesses: After evaluating each response independently, compare the two. Consider both the quality of the content and how closely it aligns with the criteria and image. Identify the strengths and weaknesses of each response, and highlight the key differences.
3. Ensure Fairness: To avoid positional bias, swap the positions of Assistant A and Assistant B after the first evaluation (i.e., make Assistant A become Assistant B and vice versa) and repeat the analysis and comparison. This ensures that each response is evaluated impartially under the same criteria.
4. Provide a Conclusion Based on Both Evaluations: After completing both evaluations (original and swapped positions), combine your analysis to provide a final verdict. If the responses are similar, with only minimal differences, your judgment should reflect that and indicate a tie.
Possible Verdict Options:
• If Assistant A is clearly better in both evaluations: [[A>>B]]• If Assistant A is slightly better in both evaluations: [[A>B]]• If both responses are nearly identical, showing minimal differences and no clear advantage: [[A=B]]• If Assistant B is slightly better in both evaluations: [[B>A]]• If Assistant B is clearly better in both evaluations: [[B>>A]]
Instructions to the AI Assistants:
[INSTRUCTIONS]{instructions}[END INSTRUCTIONS]
Assistant A Response:
[ASSISTANT A]{reference_answer_by_gpt4o}[END ASSISTANT A]
Evaluation Criteria:
[CRITERIA]{criteria}[END CRITERIA]
Assistant B Response:
[ASSISTANT B]{prediction}[END ASSISTANT B]
Output Format:
Your output should include: 1. Evaluation of Assistant A’s Response: Provide a detailed qualitative evaluation, focusing on how well Assistant A’s response aligns with the criteria and the image. 2. Evaluation of Assistant B’s Response: Provide a detailed qualitative evaluation, focusing on how well Assistant B’s response aligns with the criteria and the image. 3. Final Verdict: After considering both evaluations, select one of the following verdicts and justify it based on your analysis:
Your output format should end like this:Assistant A Evaluation: [qualitative comment]Assistant B Evaluation: [qualitative comment]Final Verdict is: [[VERDICT]]""",
##### For Visual Factuality 'objective_without_gt':"""Please act as an impartial judge and evaluate the **Visual Factuality** of the responses provided by two AI assistants to the user prompt displayed below.
The responses were generated based on the provided instructions and visual input from images. Take this context into account when making your judgment.
Steps for Evaluation:1. Evaluate visual factuality for both responses based on the visual factuality criteria. • If the visual factuality criteria consist of **X aspects**, each aspect is worth **10/X points**. • For each aspect, there may be multiple small criteria. If there are **Y small criteria in one aspect**, each small criterion is worth **10/X/Y points**.2. Assign a total score out of 10 for each response.
Instructions to the AI assistants:[INSTRUCTIONS]{instructions}[END INSTRUCTIONS]
Assistant A response:[ASSISTANT A]{reference_answer_by_gpt4o}[END ASSISTANT A]
Visual Factuality Criteria:[VISUAL FACTUALITY CRITERIA]{criteria}[END CRITERIA]
Assistant B response:[ASSISTANT B]{prediction}[END ASSISTANT B]
Your output should evaluate visual factuality scores for each assistant and end like this:
Response A Visual Factuality Score: X/10Response B Visual Factuality Score: Y/10""",
'objective_with_gt':"""Please act as an impartial judge and evaluate the **Visual Factuality** of the responses provided by two AI assistants to the user prompt displayed below.
The responses were generated based on the provided instructions and visual input from images.There is a provided ground truth for the instructions, but the ground truth was not given to the AI assistants when generating their responses.Take this context into account when making your judgment.
Steps for Evaluation:1. Evaluate visual factuality for both responses based on the provided ground truth and visual factuality criteria. • If the visual factuality criteria consist of **X aspects**, each aspect is worth **10/X points**. • For each aspect, there may be multiple small criteria. If there are **Y small criteria in one aspect**, each small criterion is worth **10/X/Y points**.2. Assign a total score out of 10 for each response.
Instructions to the AI assistants:[INSTRUCTIONS]{instructions}[END INSTRUCTIONS]
Assistant A response:[ASSISTANT A]{reference_answer_by_gpt4o}[END ASSISTANT A]
Visual Factuality Criteria:[VISUAL FACTUALITY CRITERIA]{criteria}[END CRITERIA]
Assistant B response:[ASSISTANT B]{prediction}[END ASSISTANT B]
Ground truth:[GROUND TRUTH]{groundtruth}[END GROUND TRUTH]
Your output should evaluate visual factuality scores for each assistant and end like this:
Response A Visual Factuality Score: X/10Response B Visual Factuality Score: Y/10""",}
creation_mmbench_category_dict = { 'CATEGORY_Literary_Writing': [ 'story_continue', 'landscape_to_poem', 'historical_story_creation', 'story_novel_creation', 'prose_writing_scenery', 'art_inspired_prose', 'daily_conversation_creation', 'children_book_illustration_dialogue_creation' ], 'CATEGORY_Common_Functionality_Writing':[ 'ins_simple_daily_copywriter', 'travel_journal', 'short_video_scripts_for_social_media', 'social_media_travel_content', 'daily_achievement_show_off', 'scientific_research_simple_promotion', 'twitter_comment_on_daily_news', 'personal_event_summaries', 'daily_affairs_inquiries', 'business_collaborative_email_writing', 'daily_emotional_email_writing', 'letter_of_complaint', 'daily_invitation_email_writing', 'holiday_card_writing', 'letter_of_application', 'product_usage_experience_review', 'store_experience_review', 'public_welfare_activity_participation_initiative' ], 'CATEGORY_Professional_Functionality_Writing': [ 'museum_guide_word_creation', 'recipe_infer_and_guide', 'landscape_introduction', 'drafting_announcements_for_public_spaces', 'floor_plan_renovation_design', 'teaching_plan', 'nutritional_formulation_of_recipe', 'clothing_match_design', 'software_engineering_diagram_explanation', 'event_planning_and_venue_arrangement', 'ui_design_analysis_and_optimization', 'attraction_promotional_words', 'product_marketing_strategy', 'script_writing_for_product_advertisement_promotional_video', 'residence_reasoning', 'scientific_diagram_understanding', 'pulitzer_prize_judge', 'architecture_appreciation', 'company_team_amuse_broadcast' ], 'CATEGORY_Creative_Multimodal_Understanding': [ 'travel_itinerary_planning_and_recommendations', 'photography_appreciation', 'meme_explanation', 'advertisement_explanation', 'document_understanding', 'snapshot_analysis' ]
}
def is_criteria_valid(criteria): import re for value in criteria.values(): if value == '\\' or value == '' or not re.search('[a-zA-Z]', value): return False return True
key_mapping = { "sub_parse_ok": "preference_parse_ok", "sub_dist": "preference_dist", "win_rate": "win_rate", "sub_reward": "reward", "obj_parse_ok": "visual_factuality_parse_ok", "obj_score": "visual_factuality_score", "obj_ref_score": "visual_factuality_ref_score"}
def rename_keys(data, key_mapping): if isinstance(data, dict): new_data = {} for key, value in data.items(): new_key = key_mapping.get(key, key) new_data[new_key] = rename_keys(value, key_mapping) return new_data elif isinstance(data, list): return [rename_keys(item, key_mapping) for item in data] else: return data
def build_prompt(line, dataset_name): try: criteria = eval(line['criteria']) except: criteria = line['criteria']
if isinstance(criteria, dict): new_criteria = {} for k in criteria: if 'subjective' in k.lower(): new_criteria['subjective'] = criteria[k] else: new_criteria['objective'] = criteria[k] else: assert isinstance(criteria, str) new_criteria = {'subjective': criteria} criteria = new_criteria assert 'subjective' in criteria, 'No subjective criteria found in the criteria dict'
prompts = {} if listinstr(['Creation_MMBench'], dataset_name): dataset_name = 'Creation_MMBench' prompts['subjective'] = prompt_dict[dataset_name]['subjective'].format( instructions=line['question'], criteria=criteria['subjective'], reference_answer_by_gpt4o=line['reference_answer_by_gpt4o'], prediction=line['prediction'] ) if 'objective' in criteria: if 'ground_truth' in line and (not pd.isna(line['ground_truth'])) and line['ground_truth'] != '': prompts['objective'] = prompt_dict[dataset_name]['objective_with_gt'].format( instructions=line['question'], criteria=criteria['objective'], groundtruth=line['ground_truth'], reference_answer_by_gpt4o=line['reference_answer_by_gpt4o'], prediction=line['prediction']) else: prompts['objective'] = prompt_dict[dataset_name]['objective_without_gt'].format( instructions=line['question'], criteria=criteria['objective'], reference_answer_by_gpt4o=line['reference_answer_by_gpt4o'], prediction=line['prediction']) return prompts
def Generate_Creation_MMBench_judge(model, image_list, prompt): assert isinstance(prompt, dict) response = {} for key in prompt.keys(): if image_list and key == 'subjective': input_msg = [] for img_path in image_list: if read_ok(img_path): input_msg.append({'type': 'image', 'value': img_path}) else: raise ValueError(f"Image not found: {img_path}") input_msg.append({'type': 'text', 'value': prompt[key]}) # print(f'using image {image_list} and text') response[key] = model.generate(input_msg) else: response[key] = model.generate(prompt[key]) return response
def extract_subjective(inp, dataset_name): mapping_dict = { 'LiveMMBench_Creation': 'FINAL CONCLUSION:', 'Creation_MMBench': 'FINAL VERDICT IS:' } cands = { 'A>>B', 'A>B', 'A=B', 'B>A', 'B>>A', 'B<<A', 'B<A', 'B=A', 'A<B', 'A<<B' }
lines = inp.split('\n') for line in lines: line_upper = line.upper() if mapping_dict[dataset_name] in line_upper:
match = re.search(r'\[\[\s*(.*?)\s*\]\]', line_upper) if match: rem = match.group(1).replace(' ', '') if rem in cands: return rem return None
def extract_objective(inp, dataset_name): # Response A Alignment Score: X/10 mapping_dict = { 'LiveMMBench_Creation': { 'A': 'RESPONSE A ALIGNMENT SCORE:', 'B': 'RESPONSE B ALIGNMENT SCORE:' }, 'Creation_MMBench': { 'A': 'RESPONSE A VISUAL FACTUALITY SCORE:', 'B': 'RESPONSE B VISUAL FACTUALITY SCORE:' }, } if pd.isna(inp) or inp is None or inp == '': return 'NO_OBJECTIVE' lines = inp.split('\n') a_score, b_score = None, None for line in lines: line = line.upper() line = re.sub(r"[“”*]", "", line) if line.startswith(mapping_dict[dataset_name]['A']): rem = line.split(mapping_dict[dataset_name]['A'])[1].strip() rem = rem.split('/')[0].strip() try: a_score = float(rem) except: continue elif line.startswith(mapping_dict[dataset_name]['B']): rem = line.split(mapping_dict[dataset_name]['B'])[1].strip() rem = rem.split('/')[0].strip() try: b_score = float(rem) except: continue if a_score is not None and b_score is not None and (0 <= a_score <= 10) and (0 <= b_score <= 10): return f'{a_score}|{b_score}' else: return None
def Creation_MMBench_extract(judge_response_pkl, org_data, dataset_name): import copy as cp data = cp.deepcopy(org_data) data['subjective_judge'] = [judge_response_pkl[idx]['subjective'] for idx in data['index']] data['objective_judge'] = [judge_response_pkl[idx].get('objective', None) for idx in data['index']] data['subjective_score'] = [extract_subjective(x, dataset_name) for x in data['subjective_judge']] data['objective_score'] = [extract_objective(x, dataset_name) for x in data['objective_judge']] return data
def get_dimension_rating(score_file_name, rev=False): def get_pw_score(text): if 'A<<B' in text or 'B>>A' in text: return 2 elif 'A<B' in text or 'B>A' in text: return 1 elif 'A=B' in text or 'B=A' in text: return 0 elif 'A>B' in text or 'B<A' in text: return -1 elif 'A>>B' in text or 'B<<A' in text: return -2 else: return None
score_file = load(score_file_name) base_dict = {'sub_valid': 0, 'sub_missing': 0, 'sub_score': [], 'obj_valid': 0, 'obj_missing': 0, 'obj_ref_score': [], 'obj_score': []} return_dict = {'overall': cp.deepcopy(base_dict)}
for idx, item in score_file.iterrows(): task_name = item['task_name'] if task_name not in return_dict.keys(): return_dict[task_name] = cp.deepcopy(base_dict)
if not pd.isna(item['subjective_score']): for k in ['overall', task_name]: return_dict[k]['sub_valid'] += 1 return_dict[k]['sub_score'].append(get_pw_score(item['subjective_score'])) else: return_dict['overall']['sub_missing'] += 1 return_dict[task_name]['sub_missing'] += 1
if item['objective_score'] == 'NO_OBJECTIVE': continue elif not pd.isna(item['objective_score']): score = item['objective_score'] assert '|' in score ref_score, score = [float(x) for x in score.split('|')] for k in ['overall', task_name]: return_dict[k]['obj_valid'] += 1 return_dict[k]['obj_score'].append(score) return_dict[k]['obj_ref_score'].append(ref_score) else: return_dict['overall']['obj_missing'] += 1 return_dict[task_name]['obj_missing'] += 1
final_res = {}
for k, v in return_dict.items(): res = {} res['sub_parse_ok'] = v['sub_valid'] / (v['sub_valid'] + v['sub_missing']) dist = defaultdict(lambda: 0) for x in v['sub_score']: dist[x] += 1 assert len(dist) <= 5 and sum(list(dist.values())) == v['sub_valid'] if v['sub_valid']: res['sub_dist'] = {k: dist[k] / v['sub_valid'] for k in [-2, -1, 0, 1, 2]} res['sub_reward'] = (-100 * dist[-2] - 50 * dist[-1] + 50 * dist[1] + 100 * dist[2]) / v['sub_valid']
if v['obj_valid'] + v['obj_missing']: res['obj_parse_ok'] = v['obj_valid'] / (v['obj_valid'] + v['obj_missing']) if v['obj_valid']: res['obj_score'] = sum(v['obj_score']) / v['obj_valid'] res['obj_ref_score'] = sum(v['obj_ref_score']) / v['obj_valid'] final_res[k] = res
final_res['raw'] = return_dict return final_res
def merge_dual(raw, raw_dual, dataset_name): final_res = {} category_raw = {} for k, v in raw.items(): # merge dual: {'sub_valid': 0, 'sub_missing': 0, 'sub_score': [], 'obj_valid': 0, 'obj_missing': 0, 'obj_ref_score': [], 'obj_score': []} dual_v = raw_dual[k] v['sub_valid'] += dual_v['sub_valid'] v['sub_missing'] += dual_v['sub_missing'] v['sub_score'].extend([-x for x in dual_v['sub_score']]) v['obj_valid'] += dual_v['obj_valid'] v['obj_missing'] += dual_v['obj_missing'] v['obj_score'].extend(dual_v['obj_ref_score']) v['obj_ref_score'].extend(dual_v['obj_score']) raw[k] = v
res = {} res['sub_parse_ok'] = v['sub_valid'] / (v['sub_valid'] + v['sub_missing']) dist = defaultdict(lambda: 0) for x in v['sub_score']: dist[x] += 1 assert len(dist) <= 5 and sum(list(dist.values())) == v['sub_valid'] res['sub_dist'] = {k: dist[k] / v['sub_valid'] for k in [-2, -1, 0, 1, 2]} res['win_rate'] = (dist[2] + dist[1]) / v['sub_valid'] * 100 res['sub_reward'] = (-100 * dist[-2] - 50 * dist[-1] + 50 * dist[1] + 100 * dist[2]) / v['sub_valid']
if v['obj_valid'] + v['obj_missing']: res['obj_parse_ok'] = v['obj_valid'] / (v['obj_valid'] + v['obj_missing']) if v['obj_valid']: res['obj_score'] = sum(v['obj_score']) / v['obj_valid'] res['obj_ref_score'] = sum(v['obj_ref_score']) / v['obj_valid'] final_res[k] = res
if listinstr(['Creation_MMBench'], dataset_name): pass_flag = False for main_category_name, category_list in creation_mmbench_category_dict.items(): if k in creation_mmbench_category_dict.keys() or k == 'overall': pass_flag = True break if k in category_list: if main_category_name not in category_raw.keys(): category_raw[main_category_name] = {'sub_valid': 0, 'sub_missing': 0, 'sub_score': [], 'obj_valid': 0, 'obj_missing': 0, 'obj_ref_score': [], 'obj_score': []} category_raw[main_category_name]['sub_valid'] += v['sub_valid'] category_raw[main_category_name]['sub_missing'] += v['sub_missing'] category_raw[main_category_name]['sub_score'].extend(v['sub_score']) category_raw[main_category_name]['obj_valid'] += v['obj_valid'] category_raw[main_category_name]['obj_missing'] += v['obj_missing'] category_raw[main_category_name]['obj_score'].extend(v['obj_score']) category_raw[main_category_name]['obj_ref_score'].extend(v['obj_ref_score']) pass_flag = True break if not pass_flag: raise Exception(f"Error: {k} not found in type_dict")
for k, v in category_raw.items(): res = {} res['sub_parse_ok'] = v['sub_valid'] / (v['sub_valid'] + v['sub_missing']) dist = defaultdict(lambda: 0) for x in v['sub_score']: dist[x] += 1 assert len(dist) <= 5 and sum(list(dist.values())) == v['sub_valid'] res['sub_dist'] = {k: dist[k] / v['sub_valid'] for k in [-2, -1, 0, 1, 2]} res['win_rate'] = (dist[2] + dist[1]) / v['sub_valid'] * 100 res['sub_reward'] = (-100 * dist[-2] - 50 * dist[-1] + 50 * dist[1] + 100 * dist[2]) / v['sub_valid']
if v['obj_valid'] + v['obj_missing']: res['obj_parse_ok'] = v['obj_valid'] / (v['obj_valid'] + v['obj_missing']) if v['obj_valid']: res['obj_score'] = sum(v['obj_score']) / v['obj_valid'] res['obj_ref_score'] = sum(v['obj_ref_score']) / v['obj_valid'] final_res[k] = res
final_res['raw'] = raw final_res['category_raw'] = category_raw if listinstr(['Creation_MMBench'], dataset_name): final_res = rename_keys(final_res, key_mapping) return final_res
class CreationMMBenchDataset(ImageBaseDataset):
TYPE = 'CreationVQA' DATASET_URL = { 'LiveMMBench_Creation': '', 'Creation_MMBench': 'https://opencompass.openxlab.space/utils/VLMEval/Creation_MMBench.tsv' } DATASET_MD5 = { 'Creation_MMBench':'870c0332a9c6a169d0ac9b8574c245fe' }
# It returns a dictionary def dump_image(self, line): os.makedirs(self.img_root, exist_ok=True)
if 'image' in line: if isinstance(line['image'], list): tgt_path = [] assert 'image_path' in line for img, im_name in zip(line['image'], line['image_path']): path = osp.join(self.img_root, im_name) if not read_ok(path): decode_base64_to_image_file(img, path) tgt_path.append(path) else: if 'image_path' in line: assert isinstance(line['image_path'], str) or (isinstance(line['image_path'], list) and len(line['image_path']) == 1) if isinstance(line['image_path'], list): line['image_path'] = line['image_path'][0] tgt_path = osp.join(self.img_root, line['image_path']) else: tgt_path = osp.join(self.img_root, f"{line['index']}.jpg") if not read_ok(tgt_path): decode_base64_to_image_file(line['image'], tgt_path) tgt_path = [tgt_path] else: assert 'image_path' in line tgt_path = toliststr(line['image_path'])
return tgt_path
def evaluate(self, eval_file, **judge_kwargs): rating_rev = None dual_eval = judge_kwargs.pop('dual_eval', True) if dual_eval: print('Dual Evaluation Strategy is enabled.') src = load(eval_file) tgt = load(eval_file) tgt['reference_answer_by_gpt4o'] = src['prediction'] tgt['prediction'] = src['reference_answer_by_gpt4o'] tgt_file_name = get_intermediate_file_path(eval_file, '_rev') dump(tgt, tgt_file_name) judge_kwargs['dual_eval'] = False rating_rev = self.evaluate(tgt_file_name, **judge_kwargs) judge_kwargs.pop('dual_eval', None)
score_file = get_intermediate_file_path(eval_file, '_score') tgt_file = get_intermediate_file_path(eval_file, '_rating', 'json')
model = judge_kwargs.pop('model', 'gpt-4o-0806') model_name = model.split('/')[-1] if '/' in model else model tmp_file = get_intermediate_file_path(eval_file, f'_{model_name}', 'pkl')
nproc = judge_kwargs.pop('nproc', 4)
if not osp.exists(score_file): data = load(eval_file) lt = len(data) lines = [data.iloc[i] for i in range(len(data))] judge_kwargs['max_tokens'] = 4096
model = build_judge(model=model, **judge_kwargs) assert model.working(), ('CreationMMBench evaluation requires a working OPENAI API\n' + DEBUG_MESSAGE)
prompts = [build_prompt(line, self.dataset_name) for line in lines]
indices = [line['index'] for line in lines]
if listinstr(['Creation_MMBench'], self.dataset_name): no_relative_image_list = [self.dump_image(line) for idx, line in self.data.iterrows()] assert len(no_relative_image_list) == len(lines) image_list = [] for subimage_list in no_relative_image_list: sublist = [] for image_path in subimage_list: image_path = osp.join(self.img_root, image_path) assert osp.exists(image_path), f"Image not found: {image_path}" sublist.append(image_path) image_list.append(sublist) else: image_list = [[] for _ in range(len(lines))] tups = [(model, image, prompt) for prompt, image in zip(prompts, image_list)]
ans = {} if osp.exists(tmp_file): ans = load(tmp_file) ans = {k: v for k, v in ans.items() if model.fail_msg not in str(v)} tups = [x for x, i in zip(tups, indices) if i not in ans] indices = [i for i in indices if i not in ans]
if len(indices): _ = track_progress_rich( Generate_Creation_MMBench_judge, tups, nproc=nproc, chunksize=nproc, keys=indices, save=tmp_file, ) ans = load(tmp_file) data = Creation_MMBench_extract(ans, data, self.dataset_name) dump(data, score_file)
rating = get_dimension_rating(score_file) dump(rating, tgt_file)
if dual_eval: raw = rating['raw'] rev_tgt_file = tgt_file.replace('rating.json', 'rev_rating.json') rev_raw = load(rev_tgt_file)['raw'] merged_rating = merge_dual(raw, rev_raw, self.dataset_name) dump(merged_rating, tgt_file.replace('rating.json', 'merged_rating.json')) print(f"Rating:\n{rating['overall']}\n\nDual Rating:\n{merged_rating['overall']}") return merged_rating['overall'] else: return rating['overall']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import mathfrom typing import List
from .utils.judge_util import build_judgefrom .image_base import ImageBaseDatasetfrom .mmlongbench import concat_images, MMLongBench_auxeval, anls_computefrom ..smp import *from ..smp.file import get_intermediate_file_path
FAIL_MSG = 'Failed to obtain answer via API.'
def DUDE_acc(result_file): data = load(result_file) overall_score = 0.0 score_list = list() for i in range(len(data)): item = data.iloc[i] if isinstance(item['answer'], float) and math.isnan(item['answer']): item['answer'] = 'Not answerable'
item['answer'] = item['answer'].lower() item['pred'] = item['pred'].lower() score = anls_compute(item['answer'], item['pred']) score_list.append(score) overall_score += score
data['score'] = score_list dump(data, result_file)
res = dict() res['category'], res['num'], res['avg_score'] = ['anls'], [len(data)], [overall_score / len(data)] res = pd.DataFrame(res) return res
class DUDE(ImageBaseDataset):
TYPE = 'VQA'
DATASET_URL = { 'DUDE': 'https://opencompass.openxlab.space/utils/VLMEval/DUDE.tsv', 'DUDE_MINI': 'https://opencompass.openxlab.space/utils/VLMEval/DUDE_MINI.tsv', } DATASET_MD5 = { 'DUDE': '130d860d08206e1e407cd77150c10d88', 'DUDE_MINI': 'e0c0d998114f0cca7516d12039d2b538', }
SUPPORTED_MODELS = { 'GPT4': (1, 1), 'GPT4V': (1, 1), 'GPT4V_HIGH': (1, 1), 'GPT4o': (1, 1), 'GPT4o_HIGH': (1, 1), 'GPT4o_MINI': (1, 1), 'XComposer2d5': (1, -1), 'XComposer2_4KHD': (1, -1), 'MiniCPM-Llama3-V-2_5': (1, 5), 'InternVL-Chat-V1-5': (5, 2), }
def __init__(self, dataset, **kwargs): self.model_list = list(self.SUPPORTED_MODELS.keys()) model_name = kwargs['model'] if not listinstr(self.model_list, model_name): raise AssertionError("{} doesn't support the evaluation on DUDE.".format(model_name)) super(DUDE, self).__init__(dataset)
self.is_api = True if listinstr(['GPT4'], model_name) else False self.max_pages = 120 concat_num, column_num = self.SUPPORTED_MODELS.get(model_name) self.concat_num = concat_num self.column_num = column_num
def prepare_tsv(self, url, file_md5=None): data_root = LMUDataRoot() os.makedirs(data_root, exist_ok=True) file_name = url.split('/')[-1] data_path = osp.join(data_root, file_name) if osp.exists(data_path) and (file_md5 is None or md5(data_path) == file_md5): pass else: warnings.warn('The dataset tsv is not downloaded') download_file(url, data_path) return load(data_path)
def dump_image(self, origin_line): os.makedirs(self.img_root, exist_ok=True) try: import fitz except Exception as e: logging.critical(f'{type(e)}: {e}') logging.critical('Please use `pip install pymupdf` to parse PDF files.')
line = origin_line.copy() if not isinstance(line['image_path'], List): line['image_path'] = [line['image_path']] line['image_path'] = line['image_path'][:self.max_pages] skip_pdf_parse = True for im_name in line['image_path']: path = osp.join(self.img_root, im_name) if not read_ok(path): skip_pdf_parse = False break
# Just for being compatible with the zooped loop: zip(line['image'], line['image_path']) if skip_pdf_parse: line['image'] = line['image_path'] else: pdf_data = base64.b64decode(line['image']) pdf_file = io.BytesIO(pdf_data) encoded_images = [] with fitz.open(stream=pdf_file, filetype='pdf') as doc: doc = doc[:self.max_pages] for page in doc: image = page.get_pixmap(dpi=144) image_file = io.BytesIO(image.tobytes(output='png')) image = Image.open(image_file) encoded_image = encode_image_to_base64(image) encoded_images.append(encoded_image) line['image'] = encoded_images print('process {}'.format(line['doc_id']))
if 'image' in line: if isinstance(line['image'], list): tgt_path = [] assert 'image_path' in line for img, im_name in zip(line['image'], line['image_path']): path = osp.join(self.img_root, im_name) if not read_ok(path): decode_base64_to_image_file(img, path) tgt_path.append(path) else: tgt_path = osp.join(self.img_root, f"{line['index']}.jpg") if not read_ok(tgt_path): decode_base64_to_image_file(line['image'], tgt_path) tgt_path = [tgt_path] else: assert 'image_path' in line tgt_path = toliststr(line['image_path'])
if self.concat_num > 0 and not self.is_api: concatenated_images = concat_images(tgt_path, max_concat=self.concat_num, column_num=self.column_num)
old_tgt_path = tgt_path assert isinstance(old_tgt_path, list) if self.column_num != -1: tgt_path = [ '_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat{}_{}.jpg'.format(self.concat_num, i) for i in range(len(concatenated_images)) ] else: tgt_path = ['_'.join(old_tgt_path[0].split('_')[:-1]) + '_concat_all.jpg']
for path, concatenated_image in zip(tgt_path, concatenated_images): if not read_ok(path): decode_base64_to_image_file(encode_image_to_base64(concatenated_image), path) num_images, image_size = len(old_tgt_path), concatenated_image.size print('concat {} images to a new one with size {}. save at {}'.format(num_images, image_size, path)) return tgt_path
@classmethod def evaluate(self, eval_file, **judge_kwargs): logger = get_logger('Evaluation') model = judge_kwargs['model']
storage = get_intermediate_file_path(eval_file, f'_{model}') tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl')
if osp.exists(storage): logger.warning(f'GPT scoring file {storage} already exists, will reuse it in DUDE_eval. ') else: data = load(eval_file) model = build_judge(max_tokens=128, **judge_kwargs) lt = len(data) lines = [data.iloc[i] for i in range(lt)] tups = [(model, line) for line in lines] indices = [line['index'] for line in lines]
ans = {} if osp.exists(tmp_file): ans = load(tmp_file) tups = [x for x, i in zip(tups, indices) if i not in ans] indices = [i for i in indices if i not in ans]
if len(indices): new_results = list() for model, line in tqdm(tups): res = MMLongBench_auxeval(model, line) new_results.append(res)
log_map, res_map, pred_map = {}, {}, {} all_inds = [line['index'] for line in lines] for k, v in zip(all_inds, new_results): log_map[k] = v['log'] res_map[k] = v['res'] pred_map[k] = v['pred'] data['res'] = [res_map[idx] for idx in data['index']] data['log'] = [log_map[idx] for idx in data['index']] data['pred'] = [pred_map[idx] for idx in data['index']] dump(data, storage)
score = DUDE_acc(storage) score_pth = get_intermediate_file_path(storage, '_score', 'csv')
dump(score, score_pth) logger.info(f'DUDE successfully finished evaluating {eval_file}, results saved in {score_pth}') logger.info('Score: ') logger.info(score)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193import osimport refrom tqdm import tqdmimport pandas as pd
from os import path as ospfrom .image_base import ImageBaseDatasetfrom .utils import build_judge, DEBUG_MESSAGEfrom ..smp import decode_base64_to_image_file, load, dump, get_intermediate_file_pathFAIL_MSG = 'Failed to obtain answer via API.'
class M4Bench(ImageBaseDataset): """ Dataset class for M4Bench, handling single and dual image inputs. """ TYPE = 'M4Bench'
DATASET_URL = { "State_Invariance": "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/State_Invariance.tsv", # noqa: E501 "State_Comparison": "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/State_Comparison.tsv", # noqa: E501 "Spatial_Perception": "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/Spatial_Perception.tsv", # noqa: E501 "Instance_Comparison": "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/Instance_Comparison.tsv", # noqa: E501 "Detailed_Difference": "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/Detailed_Difference.tsv" # noqa: E501 }
DATASET_MD5 = { "State_Invariance": "ad9723d478d4696dfc3b18bcaeca89b6", "State_Comparison": "41999997360a88e6e388b9a5438a45eb", "Spatial_Perception": "7059e29d15ad4379b6f0c0f1801dafe5", "Instance_Comparison": "9a7f282d0a092b617147a36693df3461", "Detailed_Difference": "f1cd60c1c1144768cd978efce5ba93a8" }
def build_prompt(self, line): """ Builds a multimodal prompt for the given data line. """ HF_HEADER = "https://huggingface.co/datasets/Anonymous8976/M4Bench/resolve/main/data/" # noqa: E501
if isinstance(line, int): line = self.data.iloc[line]
image1_base64 = line.get('image1', '') image2_base64 = line.get('image2', '') image1_url = line.get('image1_path', '') image2_url = line.get('image2_path', '')
msgs = []
if image1_base64 and image2_base64 and image1_url and image2_url: image1_base_path = image1_url.replace(HF_HEADER, '') image1_local_path = osp.join(self.img_root, image1_base_path)
image2_base_path = image2_url.replace(HF_HEADER, '') image2_local_path = osp.join(self.img_root, image2_base_path)
if not osp.exists(image1_local_path) or not osp.exists(image2_local_path): decode_base64_to_image_file(image1_base64, image1_local_path) decode_base64_to_image_file(image2_base64, image2_local_path)
# If both images are in base64 format msgs = [ dict(type='image', value=image1_local_path), dict(type='image', value=image2_local_path) ] elif image1_url and image2_url: # If both images are URLs msgs = [ dict(type='image', value=image1_url), dict(type='image', value=image2_url) ] else: raise ValueError("Both images must be provided either as base64 or URLs.") # noqa: E501
query = line['query']
msgs.append(dict(type='text', value=query)) return msgs
def evaluate(self, eval_file, **judge_kwargs): """ Evaluates the model predictions against the ground truth. """ results_df = load(eval_file)
dataset_name = None for name in self.DATASET_URL: if name in eval_file: dataset_name = name break
if dataset_name is None: raise ValueError( f"Could not determine dataset name from eval_file path: {eval_file}") # noqa: E501
# # Load ground truth data # gt_file = get_cache_path(self.DATASET_URL[dataset_name]) # gt_df = pd.read_csv(gt_file, sep='\t', on_bad_lines='warn')
# # Merge predictions with ground truth df = results_df.copy()
def get_ans(s): s = str(s) match = re.search(r'^\s*\(([A-Z])\)', s) if match: return match.group(1)
options = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') for op in options: if s.startswith(op): return op return None
if judge_kwargs: try: # Use LLM as a judge to parse the prediction judge = build_judge(**judge_kwargs)
# Prepare data for the judge def extract_question(q): return q.split('\n(')[0]
def extract_options(q): parts = q.split('\n(') return '\n('.join(parts[1:]) if len(parts) > 1 else ''
df['question_text'] = df['query'].apply(extract_question) df['options_text'] = df['query'].apply(extract_options)
prompt_tmpl = ( 'You are an AI assistant who will help me to match ' 'an answer with several options of a single-choice question. ' # noqa: E501 'You are provided with a question, several options, and an answer, ' # noqa: E501 'and you need to find which option is most similar to the answer. ' # noqa: E501 'If the meaning of all options are significantly different from the answer, output Z. ' # noqa: E501 'Your should output a single uppercase character in A, B, C, D (if they are valid options), and Z. \n' # noqa: E501 'Example 1: \n' 'Question: What is the main object in image?\nOptions: A. teddy bear B. rabbit C. cat D. dog\n' # noqa: E501 'Answer: a cute teddy bear\nYour output: A\n' 'Example 2: \n' 'Question: What is the main object in image?\nOptions: A. teddy bear B. rabbit C. cat D. dog\n' # noqa: E501 'Answer: Spider\nYour output: Z\n' 'Example 3: \n' 'Question: {question}\nOptions: {options}\nAnswer: {prediction}\nYour output: ' # noqa: E501 )
prompts = [ prompt_tmpl.format( question=row['question_text'], options=row['options_text'], prediction=row['prediction'] ) for _, row in tqdm(df.iterrows(), total=len(df), desc="Processing rows") ] parsed_pred = []
for prompt in tqdm(prompts, desc="Calling judge"): input_msg = [ { "role": "user", "content": [ {"type": "text", "value": prompt} ] } ]
_, judge_output, res = judge.generate_inner(input_msg) judge_ans = get_ans(judge_output) parsed_pred.append(judge_ans) df['parsed_pred'] = pd.Series(parsed_pred)
except Exception as e: print(f"Error during judge evaluation: {e}") print(DEBUG_MESSAGE) df['parsed_pred'] = df['prediction'].apply(get_ans) else: # Fallback to simple parsing if no judge is provided df['parsed_pred'] = df['prediction'].apply(get_ans)
# Calculate score df['score'] = (df['parsed_pred'] == df['response'])
# Save detailed results details_file = get_intermediate_file_path(eval_file, '_details') dump(df, details_file)
# Calculate and return accuracy acc = df['score'].mean() * 100 results = {'acc': acc, 'details': details_file}
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import jsonimport os
import pandas as pd
from .image_base import ImageBaseDatasetfrom ..smp import *from .utils import build_judge, DEBUG_MESSAGEfrom ..utils import track_progress_rich
def generate_prompt(d): question = d['question'] weights = eval(d['component_weight']) components = eval(d['components']) num_of_component = int(d['num_of_component']) response = d['prediction']
if num_of_component == 1: components = f"The first component is: '{components[0]}'. " score = f"The first component is worth: {weights[0]} scores. " elif num_of_component == 2: components = f"The first component is: '{components[0]}', and the second component is '{components[1]}'. " score = f"The first and second component is each worth {weights[0]} and {weights[1]} scores. " elif num_of_component == 3: components = ( f"The first component is: '{components[0]}', and the second component is '{components[1]}', " f"and the third component is '{components[2]}'. " ) score = ( "The first, second, and third component is each worth " f"{weights[0]}, {weights[1]}, and {weights[2]} scores." ) elif num_of_component == 4: components = ( f"The first component is: '{components[0]}', and the second component is '{components[1]}', " f"and the third component is '{components[2]}', and the fourth component is '{components[3]}'. " ) score = ( "The first, second, third, and fourth component is each worth " f"{weights[0]}, {weights[1]}, {weights[2]}, and {weights[3]} scores." ) elif num_of_component == 5: components = ( f"The first component is: '{components[0]}', and the second component is '{components[1]}', " f"and the third component is '{components[2]}', and the fourth component is '{components[3]}', " f"and the fifth component is '{components[4]}'. " ) score = ( "The first, second, third, fourth, and fifth component is each worth " f"{weights[0]}, {weights[1]}, {weights[2]}, {weights[3]}, and {weights[4]} scores." )
return ( "Here is an instruction for a multimodal LLM: '" f"{question}" "'. You need to grade if the response from the model follows each component of the instruction. " f"{components}" "The response is: '" f"{response}" "'. You need to score the response and be strict. The total score ranges from 0 to 10, " "depending on if the response follows the instruction. " f"{score}" "List scores of each component, and the total score in one sentence in this format: " "score of component 1: x/2, score of component 2: y/8, total score: z/10. Then explain your reasons." )
def process_rawscore(component_type, raw_score): first_sentence = raw_score.split('.')[0].split(',') score_dict = {} for i in range(len(first_sentence) - 1): score_ = first_sentence[i].split(':')[1][1:].split('/') score = int(score_[0]) / int(score_[1]) score_dict[component_type[i]] = score total_score_ = first_sentence[i + 1].split(':')[1][1:].split('/') total_score = int(total_score_[0]) / int(total_score_[1]) score_dict['total_score'] = total_score return score_dict
def get_score_dict(data, score_raw): cat_score_dict = {} for i in range(len(data)): try: cmp = data['component_type'][i][2:-2] cmp_list = cmp.split('\', \'') score_dict = process_rawscore(cmp_list, score_raw[i]) for key, val in score_dict.items(): if key not in cat_score_dict.keys(): cat_score_dict[key] = [val] else: cat_score_dict[key].append(val) except: pass cat_score_dict_average = {} for key, val in cat_score_dict.items(): cat_score_dict_average[key] = sum(val) / len(val) return cat_score_dict_average
class MIABench(ImageBaseDataset): TYPE = 'VQA'
DATASET_URL = { 'MIA-Bench': 'https://opencompass.openxlab.space/utils/VLMEval/Mia-Bench.tsv', } DATASET_MD5 = { 'MIA-Bench': '0b9de595f4dd40af18a69b94d89aba82', }
@classmethod def evaluate(self, eval_file, **judge_kwargs): judge_name = judge_kwargs.pop('model', 'gpt-4o')
model = build_judge(model=judge_name, **judge_kwargs)
storage = get_intermediate_file_path(eval_file, f'_{judge_name}') # noqa: F841 tmp_file = get_intermediate_file_path(eval_file, f'_{judge_name}', 'pkl') # noqa: F841 nproc = judge_kwargs.pop('nproc', 4) # noqa: F841
if not osp.exists(storage): data = load(eval_file) num_samples = len(data) lines = [data.loc[i] for i in range(num_samples)] prompts = [generate_prompt(line) for line in lines] org_data = MIABench('MIA-Bench').data img_map = {x: y for x, y in zip(org_data['index'], org_data['image'])} image_b64 = [img_map[idx] for idx in data['index']] indices = list(data['index']) mm_messages = [ dict(message=[ dict(type='text', value=prompt), dict(type='image', value=f'data:image/jpeg;base64,{b64}') ]) for prompt, b64 in zip(prompts, image_b64) ]
res = {} if osp.exists(tmp_file): res = load(tmp_file)
jobs = {k: v for k, v in zip(indices, mm_messages) if k not in res} job_keys = list(jobs.keys()) job_vals = [jobs[k] for k in job_keys]
resps = track_progress_rich( model.generate, job_vals, nproc=nproc, chunksize=nproc, keys=job_keys, save=tmp_file, ) for k, resp in zip(job_keys, resps): res[k] = resp data['score_raw'] = [res[idx] for idx in indices] dump(data, storage)
goresult = load(storage) results = get_score_dict(goresult, goresult['score_raw']) result_pth = get_intermediate_file_path(storage, '_score', 'csv') results_pd = pd.DataFrame.from_dict(list(results.items())) dump(results_pd, result_pth)
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257from huggingface_hub import snapshot_downloadfrom ..smp import *from ..smp.file import get_intermediate_file_path, get_file_extensionfrom .video_base import VideoBaseDatasetfrom .utils import build_judge, DEBUG_MESSAGEfrom ..utils import track_progress_rich
FAIL_MSG = 'Failed to obtain answer via API.'
def unwrap_hf_pkl(pth, suffix='.mp4'): base_dir = os.path.join(pth, 'video_pkl/') target_dir = os.path.join(pth, 'video/') pickle_files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)] pickle_files.sort()
if not os.path.exists(target_dir): os.makedirs(target_dir, exist_ok=True) for pickle_file in pickle_files: with open(pickle_file, 'rb') as file: video_data = pickle.load(file) # For each video file in the pickle file, write its contents to a new mp4 file for video_name, video_content in video_data.items(): output_path = os.path.join(target_dir, f'{video_name}{suffix}') with open(output_path, 'wb') as output_file: output_file.write(video_content) print('The video file has been restored and stored from the pickle file.') else: print('The video file already exists.')
class MMBenchVideo(VideoBaseDataset):
MD5 = '98f7df3eb1007fc375ea6fe88a98e2ff' SYS = 'You are an AI assistant responsible for answering questions about videos.' FRAMES_TMPL_PACK = """You will be provided with {} separate frames uniformly sampled from a video, \the frames are provided in chronological order of the video.Please analyze these images and provide the answer / answers to the \following question / questions about the video content.If multiple questions are provided (with indices I1, I2, I3, ...), \you should organize your answers in the following json format:{{ 'I1': 'Answer to Question I1', 'I2': 'Answer to Question I2', ...}}Otherwise, please directly reply with your response to the only question.Even if the information in these separate frames is not enough to give an answer,PLEASE GIVE A RESPONSE TO EACH OF THE QUESTIONS IN THE FORMAT DESCRIBED ABOVE."""
FRAMES_TMPL_NOPACK = """You will be provided with {} separate frames uniformly sampled from a video, \the frames are provided in chronological order of the video.Please analyze these images and provide the answer to the question about the video content.Please directly reply with your response to the only question."""
TYPE = 'Video-VQA'
def __init__(self, dataset='MMBench-Video', pack=False, nframe=0, fps=-1): super().__init__(dataset=dataset, pack=pack, nframe=nframe, fps=fps)
@classmethod def supported_datasets(cls): return ['MMBench-Video']
def prepare_dataset(self, dataset_name='MMBench-Video', repo_id='opencompass/MMBench-Video'): def check_integrity(pth): data_file = osp.join(pth, f'{dataset_name}.tsv') if md5(data_file) != self.MD5: return False data = load(data_file) for video_pth in data['video_path']: if not osp.exists(osp.join(pth, video_pth)): return False return True
cache_path = get_cache_path(repo_id) if cache_path is not None and check_integrity(cache_path): dataset_path = cache_path else: if modelscope_flag_set(): from modelscope import dataset_snapshot_download dataset_path = dataset_snapshot_download(dataset_id=repo_id) else: dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') unwrap_hf_pkl(dataset_path) self.video_path = osp.join(dataset_path, 'video/') data_file = osp.join(dataset_path, f'{dataset_name}.tsv')
return dict(data_file=data_file, root=osp.join(dataset_path, 'video'))
def build_prompt_pack(self, line): if isinstance(line, int): assert line < len(self) video = self.videos[line] elif isinstance(line, pd.Series): video = line['video'] elif isinstance(line, str): video = line
frames = self.save_video_frames(video) sub = self.data[self.data['video'] == video] sys_prompt = self.SYS + self.FRAMES_TMPL_PACK.format(len(frames)) message = [dict(type='text', value=sys_prompt)] for im in frames: message.append(dict(type='image', value=im)) nq = len(sub) prompt = 'Questions: \n{}\nAnswers: \n' qs = {int(sub.iloc[i]['index']): sub.iloc[i]['question'] for i in range(nq)} prompt = prompt.format(json.dumps(qs)) message.append(dict(type='text', value=prompt)) return message
def build_prompt_nopack(self, line, video_llm): if isinstance(line, int): assert line < len(self) line = self.data.iloc[line] if video_llm: question = line['question'] prefix, video_idx_path = os.path.split(line['video_path']) message = [dict(type='text', value=question)] message.append(dict(type='video', value=os.path.join(self.video_path, video_idx_path))) return message else: frames = self.save_video_frames(line['video']) sys_prompt = self.FRAMES_TMPL_NOPACK.format(len(frames)) message = [dict(type='text', value=sys_prompt)] for im in frames: message.append(dict(type='image', value=im)) prompt = 'Question: {}\nAnswer: '.format(line['question']) message.append(dict(type='text', value=prompt)) return message
def build_prompt(self, line, video_llm): if self.pack and not video_llm: return self.build_prompt_pack(line) else: return self.build_prompt_nopack(line, video_llm)
@staticmethod def remove_side_quote(s, syms=[',', '"', "'"]): if np.all([x in syms for x in s]): return '' while s[0] in syms: s = s[1:] while s[-1] in syms: s = s[:-1] return s
@staticmethod def robust_json_load(s): try: jsons = list(extract_json_objects(s)) assert len(jsons) == 1 return jsons[0] except: if '{' in s and s.find('{') == s.rfind('{'): sub_str = s[s.find('{') + 1:].strip() lines = sub_str.split('\n') res = {} for l in lines: l = l.strip() if ': ' in l: key = l.split(': ')[0].strip() val = l.split(': ')[1].strip() key = MMBenchVideo.remove_side_quote(key) val = MMBenchVideo.remove_side_quote(val) if len(key) and len(val): res[key] = val return res return None
def load_pack_answers(self, data_raw): vstats = defaultdict(lambda: 0) data = defaultdict(lambda: {})
for k in data_raw: ans = data_raw[k].strip() if FAIL_MSG in ans: vstats['GEN_FAIL'] += 1 continue res = self.robust_json_load(ans) if res is not None: data[k] = res vstats['PARSE_OK'] += 1 else: vstats['PARSE_FAIL'] += 1
# return data meta = cp.deepcopy(self.data) lt = len(meta) prediction = [] for i in range(lt): line = meta.iloc[i] vid = line['video'] idx = str(line['index']) prediction.append(data[vid][idx] if idx in data[vid] else None) meta['prediction'] = prediction vstats['VALIDQ'] = len([x for x in prediction if x is not None]) vstats['INVALIDQ'] = len([x for x in prediction if x is None]) return meta, vstats
# It returns a dictionary @classmethod def evaluate(self, eval_file, **judge_kwargs): from .utils.mmbench_video import get_dimension_rating, system_prompt, build_prompt
assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file' # noqa: E501 judge = judge_kwargs['model'] nproc = judge_kwargs.pop('nproc', 4)
tmp_file = get_intermediate_file_path(eval_file, f'_{judge}_tmp', 'pkl') tgt_file = get_intermediate_file_path(eval_file, f'_{judge}_rating', 'json') score_file = get_intermediate_file_path(eval_file, f'_{judge}_score')
model = build_judge(system_prompt=system_prompt, **judge_kwargs) assert model.working(), 'MMBench-Video evaluation requires a working OPENAI API\n' + DEBUG_MESSAGE
if not osp.exists(score_file): res = {} if not osp.exists(tmp_file) else load(tmp_file) res = {k: v for k, v in res.items() if model.fail_msg not in v}
data = load(eval_file) data_un = data[~data['index'].isin(res)] data_un = data_un[~pd.isna(data_un['prediction'])] lt = len(data_un) prompts = [build_prompt(data_un.iloc[i]) for i in range(lt)] indices = [data_un.iloc[i]['index'] for i in range(lt)]
if len(prompts): _ = track_progress_rich( model.generate, prompts, keys=indices, save=tmp_file, nproc=nproc, chunksize=nproc ) score_map = load(tmp_file) data['score'] = [score_map[idx] if idx in score_map else -1 for idx in data['index']] rejected = [x for x in score_map.values() if FAIL_MSG in x] data['score'] = [int(x) if istype(x, int) else -1 for x in data['score']] print( f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(score_map)} questions, ' f'failed to obtain the score for another {len(rejected)} questions. ' f'Those questions will be counted as 0 score in ALL rating, and will not be counted in VALID rating.' )
dump(data, score_file)
rating = get_dimension_rating(score_file) dump(rating, tgt_file) return rating123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483# flake8: noqaimport re
from .image_base import ImageBaseDatasetfrom .utils import build_judge, DEBUG_MESSAGEfrom ..smp import *from ..smp.file import get_intermediate_file_pathfrom ..utils import track_progress_richfrom ..dataset.utils.mmif.function_and_compare import *
logger = get_logger("MMIFEval")
aux_data_dict = {}judge_model = None
# img_dict = {}# <<< prompt >>>
def generate_eval_pt_c_level(constraints, prediction): constraints_str = "\n".join( [f"Constraint_{i + 1}: {constraint['value']}" for i, constraint in enumerate(constraints)] ) pt = f"""\Your task is to evaluate whether the response from an AI assistant adheres to all of the given constraints. \Please follow the requirements below to make the judgment:1. Be strict and consistent in your assessment.2. You should refer to the content of image to make the judgment.3. For each constraint, if the response fails to fully meet the constraint, \give it a score of 0. Otherwise, give it a score of 1.
<start of response>{prediction}<end of response>
<start of constraint list>{constraints_str}<end of constraint list>
You must evaluate and provide an explanation for each constraint listed, ensuring no constraint is omitted. \At the end, summarize the scores for all constraints in one sentence.
Your output should strictly follow the format below:Judgement: ...Summary: Score of constraint_1: x/1, Score of constraint_2: x/1, Score of constraint_3: x/1, ..., Score of \constraint_n: x/1.""" return pt
def generate_eval_pt_p_level(question, prediction, ground_truth): pt = f"""\You are an expert evaluator. Your task is to extract the answer from the model output and \compare it with the ground truth list \to determine whether the model answer covers all the points in the ground truth list. \The ground truth list is provided as a JSON array of strings, and the model answer is a text string. \An answer is considered correct if every element from the ground truth list appears in the model \answer (substring matching is acceptable). \The order does not matter. \
Your response should only be 'right' if the model answer fully covers the ground truth, or 'wrong' if it does not. \Do not provide any additional commentary.
Question: {question}Response from the model: {prediction}Ground Truth List: {ground_truth}""" return pt
def generate_cmp_pt(constraint, pred_with_constraint, pred_without_constraint): pt = f"""\You are an expert in judging whether the respone follow the given constraint. \Your task is to assess whether the model's response satisfies \the given constraint and return True or False. I will provide you \with the constraint and the model's response under this constraint. \To assist with your evaluation, I will also provide you with the model's response \to the same question without the constraint.
<start of constraint>{constraint}<end of constraint>
<start of response under the constraint>{pred_with_constraint}<end of response under the constraint>
<start of response without the constraint>{pred_without_constraint}<end of response without the constraint>
**Please follow the steps below to evaluate**:Step 1. Compare the model's response under the constraint with its response without the constraint. \If you believe these two answers \are very similar, it means the model has not fully considered the impact of the constraint on the answer. \Please return False.Step 2. Compare the model's response under the constraint with the content of the constraint. If you believe the model's response \does not meet the requirements specified in the constraint, return False. Otherwise, \if the response effectively satisfies the constraint, return True.
Start by briefly explaining your reasoning based on the above steps. At the end, provide a one-sentence \summary of your evaluation.
Your output must strictly follow this format:Reasoning: ...Summary: "True" / "False".""" return pt
# <<< re >>># extract score from gpt_resp# format: Score of instruction: x/1, Score of constraint_1: y/1, Score of constraint_2: z/1, ..., Score of constraint_n: w/1.# return: score_dict {'instruction': x/1, 'constraint_1': y/1,# 'constraint_2': z/1, ..., 'constraint_n': w/1}
def extract_score_from_direct_gpt_resp(raw_score): # Define regular expression patterns (updated to handle underscores in # constraint names) score_pattern = re.compile(r"Score\s+of\s+([a-zA-Z0-9_\-]+):\s*(\d+)\s*/\s*(\d+)", re.IGNORECASE)
# Clean the raw score to remove unnecessary symbols (e.g., newlines, # multiple spaces) # Normalize whitespace cleaned_score = re.sub(r"\s+", " ", raw_score).strip() # delete all the '*' cleaned_score = re.sub(r"\*", "", cleaned_score)
# Find all individual component scores score_matches = score_pattern.findall(cleaned_score)
# If no valid score matches found, print and raise an exception if not score_matches: raise ValueError("raw_score format is incorrect, cannot parse scores")
score_dict = {}
# Parse each component score for match in score_matches: component_name = match[0].strip().lower() # Component name, converted to lowercase component_name = component_name.replace(" ", "_") numerator = int(match[1]) # Numerator denominator = int(match[2]) # Denominator score = numerator / denominator # Calculate the score score_dict[component_name] = score # Store it in the dictionary
return score_dict
# extract score from gpt_resp# format: right or wrong# return: score
def extract_score_from_p_level_gpt_resp(raw_score): if raw_score == "right": return 1 elif raw_score == "wrong": return 0 else: # try to find "right" or "wrong" in the raw_score if re.search(r"right", raw_score, re.IGNORECASE): return 1 elif re.search(r"wrong", raw_score, re.IGNORECASE): return 0 else: raise ValueError("raw_score format is incorrect, cannot parse scores")
# extract score from gpt_resp# format: True or False# return: score
def extract_score_from_cmp_gpt_resp(response_text): # Step 1: Find the last occurrence of 'summary:' summary_idx = response_text.lower().rfind("summary") if summary_idx == -1: raise ValueError("No 'summary' found in response.")
# Step 2: Slice the string after 'summary:' and extract value after_summary = response_text[summary_idx + len("summary") :]
# Match true/false ignoring markdown and formatting match = re.search(r"\b(true|false)\b", after_summary, re.IGNORECASE) if match: value = match.group(1).lower() return 1 if value == "true" else 0
raise ValueError("No valid 'True' or 'False' found after 'summary'.")
# <<< gpt >>>
def run_once_with_image(pt, image, retry=4): global judge_model prefix = "data:image/jpeg;base64," img = prefix + image messages = [dict(type="text", value=pt), dict(type="image", value=img)] while retry: try: ans = judge_model.generate(messages) return ans except Exception as e: logger.info(f"Error in run_once_with_image: {e}") retry -= 1 return ans
def run_once_without_image(pt, retry=3): global judge_model messages = [ dict(type="text", value=pt), ] while retry: try: ans = judge_model.generate(messages) return ans except Exception as e: logger.info(f"Error in run_once_without_image: {e}") retry -= 1 return ans
# <<< score >>>
def judge_one_item(item, retry=3): global aux_data_dict item = json.loads(item) num_retry = 0 while num_retry < retry: if item.get("tag", None) == "P-Level": # in tsv file, answer is a string, need to be converted to list pt = generate_eval_pt_p_level(item["question"], item["prediction"], json.loads(item["answer"])) gpt_resp = run_once_without_image(pt) try: score = extract_score_from_p_level_gpt_resp(gpt_resp) return ( 0, "success", { "total_score": score, "gpt_resp": gpt_resp, }, ) except Exception as e: logger.error(f"\nError:\n{e}\nItem:\n{item}\ngpt_resp:\n{gpt_resp}\n") num_retry += 1 continue else: # process C-Level data # split into direct_gpt and other # direct_gpt can be processed in batch # other needs to be processed one by one constraint_direct_gpt = [] constraint_other = [] for constraint in json.loads(item["constraints"]): method = constraint["judge"]["method"] if method == "direct_gpt": constraint_direct_gpt.append(constraint) else: constraint_other.append(constraint) score_dict = {} # 1. process direct_gpt: if there is no direct_gpt, instruction is also # needed if len(constraint_direct_gpt) > 0: pt_direct_gpt = generate_eval_pt_c_level(constraint_direct_gpt, item["prediction"]) gpt_resp = run_once_with_image(pt_direct_gpt, item["image"]) try: direct_gpt_score_dict = extract_score_from_direct_gpt_resp(gpt_resp) score_dict["gpt_resp_direct_gpt"] = gpt_resp for i, constraint in enumerate(constraint_direct_gpt): score_dict[constraint["key"]] = direct_gpt_score_dict[f"constraint_{i + 1}"] except Exception as e: logger.error( f"\nError:\n{e}\nItem:\n{item}\npt_direct_gpt:\n{pt_direct_gpt}\ngpt_resp:\n{gpt_resp}" ) num_retry += 1 continue # 2. process rule_based for constraint in constraint_other: if constraint["judge"]["method"] == "rule_based": # call function according to constraint["judge"]["verify_funcs"] # maybe a list of function names (str) # func in function_and_compare.py # example: {"method": "rule_based", "verify_funcs": [{"func": # "check_whether_response_paragraph_number_in_range", "params": # [3, 3]}]}} score = 1.0 # breakpoint() for func_dict in constraint["judge"]["verify_funcs"]: func = globals()[func_dict["func"]] # use * to unpack the list, ** is used for dict judge_result = func(item["prediction"], *func_dict["params"]) # breakpoint() if not judge_result: # False -> score = 0 score = 0.0 break # breakpoint() score_dict[constraint["key"]] = score # 3. process cmp_gpt for constraint in constraint_other: if constraint["judge"]["method"] == "cmp_gpt": del_cons_prediction = aux_data_dict[item["id"]][constraint["key"]] pt = generate_cmp_pt(constraint["value"], item["prediction"], del_cons_prediction) gpt_resp = run_once_without_image(pt) try: score = extract_score_from_cmp_gpt_resp(gpt_resp) score_dict[constraint["key"]] = score score_dict[f"gpt_resp_cmp_gpt_{constraint['key']}"] = gpt_resp except Exception as e: logger.error(f"\nError:\n{e}\nItem:\n{item}\ngpt_resp:\n{gpt_resp}") num_retry += 1 continue # add total_score total_score = 0.0 cnt = 0 for key, value in score_dict.items(): if key.startswith("gpt_resp_"): continue total_score += value cnt += 1 score_dict["total_score"] = total_score / cnt logger.info(f"score_dict:\n{score_dict}") return 0, "success", score_dict return 1, "C-Level, fail in judge", {}
class MMIFEval(ImageBaseDataset): TYPE = "VQA"
# TODO: add dataset url and md5 DATASET_URL = {"MM-IFEval": 'https://opencompass.openxlab.space/utils/VLMEval/MM-IFEval.tsv'} DATASET_MD5 = { "MM-IFEval": '973bb839961a449565073a5ee70ae7a6' }
# Given one data record, return the built prompt (a multi-modal message), can override # Actually, all lines have single image def build_prompt(self, line): if isinstance(line, int): line = self.data.iloc[line]
if self.meta_only: tgt_path = toliststr(line["image_path"]) else: tgt_path = self.dump_image(line)
question = line["question"]
# save images for evaluation # global img_dict # img_dict[line["index"]] = line["image"]
msgs = [] if isinstance(tgt_path, list): msgs.extend([dict(type="image", value=p) for p in tgt_path]) else: msgs = [dict(type="image", value=tgt_path)]
# WildVision adopts text first msgs = [dict(type="text", value=question)] + msgs
return msgs
# score for the infer file # @classmethod
def evaluate(self, eval_file, **judge_kwargs): raw_bench_data = MMIFEval("MM-IFEval").data global aux_data_dict model = judge_kwargs["model"] storage = get_intermediate_file_path(eval_file, f"_{model}", "jsonl") score_file = get_intermediate_file_path(eval_file, f"_{model}_score", "csv") tmp_file = get_intermediate_file_path(eval_file, f"_{model}_tmp", "pkl") nproc = judge_kwargs.pop("nproc", 4)
data_all = load(eval_file).to_dict(orient="records")
main_data = [] aux_data = [] for i, line in enumerate(data_all): if line.get("infer_type", None) == "main": main_data.append(line) else: aux_data.append(line)
line["image"] = raw_bench_data.iloc[i]["image"]
aux_data_dict = {} for line in aux_data: assert line["infer_type"] == "aux_cmp_gpt" del_cons = line["del_cons"] if line["id"] not in aux_data_dict: aux_data_dict[line["id"]] = {} aux_data_dict[line["id"]][del_cons] = line["prediction"]
# params params_all = [json.dumps(item) for item in main_data] indices_all = [line["id"] for line in main_data]
ans = {} if os.path.exists(tmp_file): ans_tuples = load(tmp_file) for k, v in ans_tuples.items(): if v[0] == 0: ans[k] = {"eval_ret_code": v[0], "eval_msg": v[1], "eval_score_dict": v[2]} # ans is a dict logger.info(f"Tmp file exists, loaded {len(ans)} data from {tmp_file}")
tups = [x for x, i in zip(params_all, indices_all) if i not in ans] indices = [i for i in indices_all if i not in ans]
# judge if not osp.exists(storage): # judge_kwargs['system_prompt'] = SYSTEM_PROMPT judge_kwargs["temperature"] = 0 judge_kwargs["img_detail"] = "high" judge_kwargs["timeout"] = 300 global judge_model judge_model = build_judge(max_tokens=4096, **judge_kwargs)
assert judge_model.working(), "MMIFEval evaluation requires a working OPENAI API\n" + DEBUG_MESSAGE
if len(indices): new_results = track_progress_rich( judge_one_item, tups, nproc=nproc, chunksize=nproc, keys=indices, save=tmp_file, ) for k, v in zip(indices, new_results): ans[k] = {"eval_ret_code": v[0], "eval_msg": v[1], "eval_score_dict": v[2]} else: for k, v in ans.items(): if isinstance(v, tuple): ans[k] = {"eval_ret_code": v[0], "eval_msg": v[1], "eval_score_dict": v[2]} for item in main_data: item.pop("image")
for item in main_data: item["eval_ret_code"] = ans[item["id"]]["eval_ret_code"] item["eval_msg"] = ans[item["id"]]["eval_msg"] item["eval_score_dict"] = ans[item["id"]]["eval_score_dict"] # storage is a jsonl file with open(storage, "w") as f: for item in main_data: f.write(json.dumps(item) + "\n")
eval_data = load(storage) # eval_data = [json.loads(line) for line in eval_data] # calculate P-Level scores p_level_score_sum = 0 c_level_score_sum = 0 p_level_cnt = 0 c_level_cnt = 0 for line in eval_data: if line["tag"] == "P-Level": p_level_score_sum += line["eval_score_dict"]["total_score"] p_level_cnt += 1 elif line["tag"] == "C-Level": c_level_score_sum += line["eval_score_dict"]["total_score"] c_level_cnt += 1 p_level_accuracy = p_level_score_sum / p_level_cnt c_level_accuracy = c_level_score_sum / c_level_cnt # save to score_file score_dict = { "p_level_accuracy": [p_level_accuracy], "c_level_accuracy": [c_level_accuracy], "p_level_cnt": [p_level_cnt], "c_level_cnt": [c_level_cnt], "overall_accuracy": [ (p_level_accuracy * p_level_cnt + c_level_accuracy * c_level_cnt) / (p_level_cnt + c_level_cnt) ], } score_df = pd.DataFrame(score_dict) dump(score_df, score_file)
return score_df123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354# flake8: noqaimport huggingface_hubfrom huggingface_hub import snapshot_downloadfrom ..smp import *from ..smp.file import get_intermediate_file_path, get_file_extensionfrom .video_concat_dataset import ConcatVideoDatasetfrom .video_base import VideoBaseDatasetfrom .utils import build_judge, DEBUG_MESSAGEfrom ..utils import track_progress_richimport torchvision.transforms as Tfrom torchvision import transformsfrom torchvision.transforms.functional import InterpolationModeimport pandas as pdimport imageioimport cv2import zipfileimport osimport globfrom .utils.qbench_video import *
FAIL_MSG = 'Failed to obtain answer via API.'
class QBench_Video(ConcatVideoDataset): def __init__(self, dataset='QBench_Video', nframe=0, fps=-1): self.DATASET_SETS[dataset] = ['QBench_Video_MCQ','QBench_Video_VQA'] super().__init__(dataset=dataset, nframe=nframe, fps=fps)
@classmethod def supported_datasets(cls): return ['QBench_Video']
def evaluate(self, eval_file, **judge_kwargs): result = super().evaluate(eval_file=eval_file, **judge_kwargs) score_file = get_intermediate_file_path(eval_file, '_acc') result.at['open_ended', 'acc'] /= 2 dump(result, score_file) return result
class QBench_Video_MCQ(VideoBaseDataset):
MD5 = '9d6760d75fa80aa9fd5e5cf1ea274ace'
FRAMES_TMPL_SYS = """You will receive {} distinct frames that have been uniformly sampled from a video sequence, arranged in the same temporal order as they appear in the video.Please analyze these frames and answer the question based on your observations."""
FRAMES_TMPL_SYS_4VIDEO_LLM = """You will receive several distinct frames that have been uniformly sampled from a video sequence, arranged in the same temporal order as they appear in the video.Please analyze these frames and answer the question based on your observations."""
POST_PROMPT = """Please answer the question in the following format: the uppercase letter of the correct answer option itself.Please do not add any other answers beyond this."""
TYPE = 'Video-MCQ'
def __init__(self, dataset='qbenchvideo_single_MCQ', nframe=0, fps=-1): dataset_tsv_name = 'qbenchvideo_single_MCQ' super().__init__(dataset=dataset_tsv_name, nframe=nframe, fps=fps)
@classmethod def supported_datasets(cls): return ['QBench_Video_MCQ']
def prepare_dataset(self, dataset_name='qbenchvideo_single_MCQ', repo_id='zhangzicheng/Q-Bench-Video'): def check_integrity(pth): data_file = osp.join(pth, f'{dataset_name}.tsv')
if not os.path.exists(data_file): return False
if md5(data_file) != self.MD5: return False
data = load(data_file) for idx, item in data.iterrows(): if not osp.exists(os.path.normpath(osp.join(pth, item['video_path']))): return False return True
cache_path = get_cache_path(repo_id) if cache_path is not None and check_integrity(cache_path): dataset_path = cache_path else: def unzip_videos(pth): if not osp.exists(osp.join(pth, 'video')): zip_file = osp.join(pth, 'video.zip') with zipfile.ZipFile(zip_file, 'r') as zip_ref: zip_ref.extractall(pth) dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') unzip_videos(dataset_path)
data_file = osp.join(dataset_path, f'{dataset_name}.tsv') return dict(root=dataset_path, data_file=data_file)
def save_video_frames(self, line): video = line['video'] vid_path = os.path.normpath(os.path.join(self.data_root, line['video_path'])) import decord vid = decord.VideoReader(vid_path) video_info = { 'fps': vid.get_avg_fps(), 'n_frames': len(vid), } if self.nframe > 0 and self.fps < 0: step_size = len(vid) / (self.nframe + 1) indices = [int(i * step_size) for i in range(1, self.nframe + 1)] frame_paths = self.frame_paths(video) elif self.fps > 0: # not constrained by num_frames, get frames by fps total_duration = video_info['n_frames'] / video_info['fps'] required_frames = int(total_duration * self.fps) step_size = video_info['fps'] / self.fps indices = [int(i * step_size) for i in range(required_frames)] frame_paths = self.frame_paths_fps(video, len(indices))
flag = np.all([osp.exists(p) for p in frame_paths])
if not flag: lock_path = osp.splitext(vid_path)[0] + '.lock' with portalocker.Lock(lock_path, 'w', timeout=30): if not np.all([osp.exists(p) for p in frame_paths]): images = [vid[i].asnumpy() for i in indices] images = [Image.fromarray(arr) for arr in images] for im, pth in zip(images, frame_paths): if not osp.exists(pth): im.save(pth)
return frame_paths
def save_video_into_images(self, line): frame_paths = self.save_video_frames(line) return frame_paths
def build_prompt(self, line, video_llm): if isinstance(line, int): assert line < len(self) line = self.data.iloc[line]
# message = [dict(type='text', value=line['question'])] video_path = os.path.normpath(os.path.join(self.data_root, line['video_path'])) if video_llm: message = [dict(type='text', value=self.FRAMES_TMPL_SYS_4VIDEO_LLM)] message.append(dict(type='text', value=line['question'])) message.append(dict(type='video', value=video_path)) else: img_frame_paths = self.save_video_into_images(line) message = [dict(type='text', value=self.FRAMES_TMPL_SYS.format(len(img_frame_paths)))] message.append(dict(type='text', value=line['question'])) for im in img_frame_paths: message.append(dict(type='image', value=im)) message.append(dict(type='text', value=self.POST_PROMPT)) return message
@classmethod def evaluate(self, eval_file, **judge_kwargs): assert get_file_extension(eval_file) in ['xlsx', 'json', 'tsv'], 'data file should be an supported format (xlsx/json/tsv) file'
tmp_file = get_intermediate_file_path(eval_file, '_tmp', 'pkl') score_file = get_intermediate_file_path(eval_file, '_score')
if not osp.exists(score_file): model = judge_kwargs.setdefault('model', 'exact_matching') assert model in ['exact_matching']
res = {} if not osp.exists(tmp_file) else load(tmp_file) res = {k: v for k, v in res.items() if FAIL_MSG not in v}
data = load(eval_file) data_un = data[~pd.isna(data['prediction'])]
for idx in data['index']: ans = data.loc[data['index'] == idx, 'answer'].values[0] pred = data.loc[data['index'] == idx, 'prediction'].values[0] correct_choice = ans.split('.')[0].strip() correct_answer = ans.split('.')[1].strip()
if FAIL_MSG in pred: data.loc[idx, 'score'] = -1 else: data.loc[idx, 'score'] = int(check_ans_mcq( pred, ans, correct_choice, correct_answer ))
rejected = [x for x in data['score'] if x == -1]
print( f'Among {len(data)} questions, failed to obtain prediction for {len(data) - len(data_un)} questions, ' f'failed to obtain the score for another {len(rejected)} questions. ' f'Those questions will be counted as -1 score in ALL rating, and will not be counted in VALID rating.' )
dump(data, score_file)
rating = get_dimension_rating(score_file) return rating
class QBench_Video_VQA(VideoBaseDataset):
MD5 = '49e6181b341c934d0b33ec78bdcc0a3d'
FRAMES_TMPL_SYS = """You will receive {} distinct frames that have been uniformly sampled from a video sequence, arranged in the same temporal order as they appear in the video.Please analyze these frames and provide a detailed and accurate answer from the perspective of visual quality based on your observations."""
FRAMES_TMPL_SYS_4VIDEO_LLM = """You will receive several distinct frames that have been uniformly sampled from a video sequence, arranged in the same temporal order as they appear in the video.Please analyze these frames and provide a detailed and accurate answer from the perspective of visual quality based on your observations."""
TYPE = 'Video-VQA'
def __init__(self, dataset='qbenchvideo_single_VQA', nframe=0, fps=-1): dataset_tsv_name = 'qbenchvideo_single_VQA' super().__init__(dataset=dataset_tsv_name, nframe=nframe, fps=fps)
@classmethod def supported_datasets(cls): return ['QBench_Video_VQA']
def prepare_dataset(self, dataset_name='qbenchvideo_single_VQA', repo_id='zhangzicheng/Q-Bench-Video'): def check_integrity(pth): data_file = osp.join(pth, f'{dataset_name}.tsv')
if not os.path.exists(data_file): return False
if md5(data_file) != self.MD5: return False
data = load(data_file) for idx, item in data.iterrows(): if not osp.exists(os.path.normpath(osp.join(pth, item['video_path']))): return False return True
cache_path = get_cache_path(repo_id) if cache_path is not None and check_integrity(cache_path): dataset_path = cache_path else: def unzip_videos(pth): if not osp.exists(osp.join(pth, 'video')): zip_file = osp.join(pth, 'video.zip') with zipfile.ZipFile(zip_file, 'r') as zip_ref: zip_ref.extractall(pth) dataset_path = snapshot_download(repo_id=repo_id, repo_type='dataset') unzip_videos(dataset_path)
data_file = osp.join(dataset_path, f'{dataset_name}.tsv') return dict(root=dataset_path, data_file=data_file)
def save_video_frames(self, line): video = line['video'] vid_path = os.path.normpath(os.path.join(self.data_root, line['video_path'])) import decord vid = decord.VideoReader(vid_path) video_info = { 'fps': vid.get_avg_fps(), 'n_frames': len(vid), } if self.nframe > 0 and self.fps < 0: step_size = len(vid) / (self.nframe + 1) indices = [int(i * step_size) for i in range(1, self.nframe + 1)] frame_paths = self.frame_paths(video) elif self.fps > 0: # not constrained by num_frames, get frames by fps total_duration = video_info['n_frames'] / video_info['fps'] required_frames = int(total_duration * self.fps) step_size = video_info['fps'] / self.fps indices = [int(i * step_size) for i in range(required_frames)] frame_paths = self.frame_paths_fps(video, len(indices))
flag = np.all([osp.exists(p) for p in frame_paths])
if not flag: lock_path = osp.splitext(vid_path)[0] + '.lock' with portalocker.Lock(lock_path, 'w', timeout=30): if not np.all([osp.exists(p) for p in frame_paths]): images = [vid[i].asnumpy() for i in indices] images = [Image.fromarray(arr) for arr in images] for im, pth in zip(images, frame_paths): if not osp.exists(pth): im.save(pth)
return frame_paths
def save_video_into_images(self, line): frame_paths = self.save_video_frames(line) return frame_paths
def build_prompt(self, line, video_llm): if isinstance(line, int): assert line < len(self) line = self.data.iloc[line]
video_path = os.path.normpath(os.path.join(self.data_root, line['video_path'])) if video_llm: message = [dict(type='text', value=self.FRAMES_TMPL_SYS_4VIDEO_LLM)] message.append(dict(type='text', value=line['question'])) message.append(dict(type='video', value=video_path)) else: img_frame_paths = self.save_video_into_images(line) message = [dict(type='text', value=self.FRAMES_TMPL_SYS.format(len(img_frame_paths)))] message.append(dict(type='text', value=line['question'])) for im in img_frame_paths: message.append(dict(type='image', value=im)) return message
@classmethod def evaluate(self, eval_file, **judge_kwargs): model = judge_kwargs.setdefault('model', 'gpt-4o-0806') assert model in ['gpt-4o-0806', 'gpt-4o']
score_file = get_intermediate_file_path(eval_file, f'_{model}_score') tmp_file = get_intermediate_file_path(eval_file, f'_{model}', 'pkl') nproc = judge_kwargs.pop('nproc', 4)
if not osp.exists(score_file): data = load(eval_file) model = build_judge(system_prompt=VQA_JUDGE_SYS_PROMPT, **judge_kwargs) lt = len(data) lines = [data.iloc[i] for i in range(lt)] tups = [(model, line) for line in lines] indices = [line['index'] for line in lines]
ans = {} if osp.exists(tmp_file): ans = load(tmp_file) tups = [x for x, i in zip(tups, indices) if i not in ans] indices = [i for i in indices if i not in ans]
if len(indices): _ = track_progress_rich( check_ans_vqa, tups, nproc=nproc, chunksize=nproc, keys=indices, save=tmp_file, ) ans = load(tmp_file) for idx in ans: data.loc[data['index'] == idx, 'score'] = int(ans[idx].replace('Score:', '').strip()) dump(data, score_file)
rating = get_dimension_rating(score_file) return rating12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from abc import abstractmethodfrom ..smp import *
class TextBaseDataset: MODALITY = 'TEXT' DATASET_URL = {} DATASET_MD5 = {}
def __init__(self, dataset='MMBench', **kwargs): self.dataset_name = dataset
data = self.load_data(dataset)
data['index'] = [str(x) for x in data['index']]
if np.all([istype(x, int) for x in data['index']]): data['index'] = [int(x) for x in data['index']]
self.data = data self.post_build(dataset)
def __len__(self): return len(self.data)
def __getitem__(self, idx): return dict(self.data.iloc[idx])
def prepare_tsv(self, url, file_md5=None): data_root = LMUDataRoot() os.makedirs(data_root, exist_ok=True) update_flag = False file_name = url.split('/')[-1] data_path = osp.join(data_root, file_name) if osp.exists(data_path) and (file_md5 is None or md5(data_path) == file_md5): pass else: warnings.warn('The dataset tsv is not downloaded') download_file(url, data_path) update_flag = True
if file_size(data_path, 'GB') > 1: local_path = data_path.replace('.tsv', '_local.tsv') if not osp.exists(local_path) or os.environ.get('FORCE_LOCAL', None) or update_flag: from ..tools import LOCALIZE LOCALIZE(data_path, local_path) data_path = local_path return load(data_path)
def dump_image(self, line): return []
def display(self, line): if isinstance(line, int): line = self.data.iloc[line] assert isinstance(line, pd.Series) or isinstance(line, dict) mmqa_display(line)
# Return a list of dataset names that are supported by this class, can override @classmethod def supported_datasets(cls): return list(cls.DATASET_URL)
# Given the dataset name, return the dataset as a pandas dataframe, can override def load_data(self, dataset): url = self.DATASET_URL[dataset] file_md5 = self.DATASET_MD5[dataset] return self.prepare_tsv(url, file_md5)
# Post built hook, will be called after the dataset is built, can override def post_build(self, dataset): pass
# Given one data record, return the built prompt (a multi-modal message), can override def build_prompt(self, line): if isinstance(line, int): line = self.data.iloc[line]
question = line['question']
msgs = [] msgs.append(dict(type='text', value=question)) return msgs
# Given the prediction file, return the evaluation results in the format of a dictionary or pandas dataframe @abstractmethod def evaluate(self, eval_file, **judge_kwargs): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# MEGA-Bench: Scaling Multimodal Evaluation to over 500 Real-World Tasks [ICLR 2025]

MEGA-Bench contains 505 multimodal tasks with diverse data sources, input/output formats, and skill requirements. The taxonomy tree is derived from the application dimension, which guides and calibrates the annotation process. The benchmark is equiped with a suite of 45 evaluation metrics to handle various output formats beyond multiple-choice questions.
Following this doc, the evaluation result contains the final scores and multi-dimensional breakdown, which has a consistent format as [MEGA-Bench Leaderboard](https://huggingface.co/spaces/TIGER-Lab/MEGA-Bench). Below is an example from evaluating `Qwen-2-VL-7B-Instruct` on the core set.
## Step-1: Install requirements for MEGA-Bench metrics to obtain the evaluation scores and breakdown analysis
```bashpip install -r vlmeval/dataset/utils/megabench/requirements.txt```
## Step-2: Get the model response and evaluation score files with VLMEvalKit
```bash# Core set (440 tasks, in 16-frame setting)python3 run.py \ --data MEGABench_core_16frame \ --model Qwen2-VL-7B-Instruct \ --work-dir your/work/dir \
# Open-ended set (65 tasks, in 16-frame setting)python3 run.py \ --data MEGABench_open_16frame \ --model Qwen2-VL-7B-Instruct \ --work-dir your/work/dir \```Note: please set up the `OPENAI_API_KEY` in the .env file to evaluate the open set.
Then you can have 2 score files in the directory like:
```bashyour/work/dir/Qwen-2-VL-7B-Instruct/T20250706_Gbf63ab2c/megabench_score_core.jsonyour/work/dir/Qwen-2-VL-7B-Instruct/T20250707_Gbf63ab2c/megabench_score_open.json```
## Step-3(Optional): Run MEGA-Bench scripts to obtain the breakdown analysis
Move the 2 score files into the same directory, then run the script:
```bash# Run the metrics for the open-ended setcd vlmeval/dataset/utils/megabench/toolspython3 derive_breakdown_results.py --input_dir your/dir/to/megabench_scores```
The results in `your/dir/to/megabench_scores/analysis` are what used by [MEGA-Bench leaderboard](https://huggingface.co/spaces/TIGER-Lab/MEGA-Bench). The leaderboard can be updated by putting the files in the results directory of the leadboard's [HuggingFace space](https://huggingface.co/spaces/TIGER-Lab/MEGA-Bench/tree/main/static/eval_results/Default).12345from .aggregation_type import AggregationTypefrom .metric_type import MetricTypefrom .response_parse_type import ResponseParseType
__all__ = [AggregationType, MetricType, ResponseParseType]1234567891011121314from numbers import Numberfrom typing import Dict
class MinAggregation: """Take the minimum of all valid scores."""
@staticmethod def aggregate(scores: Dict[str, Number], weights: Dict[str, Number]) -> Number: """Exact match between targets and responses.""" filtered_scores = [s for s in scores.values() if s >= 0] if not filtered_scores: return -1 return min(filtered_scores)12345678910111213141516171819202122232425from enum import Enum
class AggregationType(Enum): MEAN = 0
@classmethod def from_string(cls, s): return cls.MEAN
def aggregate(self, field_scores, field_weights): if not field_scores: return 0.0
total_score = 0.0 total_weight = 0.0
for field, score in field_scores.items(): weight = field_weights.get(field, 1.0) try: total_score += score * weight except: total_score += score[0] * weight total_weight += weight
return total_score / total_weight if total_weight > 0 else 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399import argparseimport jsonimport osfrom typing import Any, Dict, Listimport astfrom vlmeval import load, dump
from . import MetricType, AggregationType, ResponseParseTypefrom .parsing.common.utils import evaluate_as_string
class MEGABenchEvaluator: def __init__( self, subset_name: str, responses_file: str, output_file: str, ): """ :param hf_data_file: Path to a file containing HF dataset tasks + their metric configs :param model_responses_file: Path to a JSON file with tasks + model responses :param output_file: Path to store evaluated results """ self.hf_data = self._load_hf(subset_name) # e.g. same structure used previously self.data = self._load_json(responses_file) # The model's output self.output_file = output_file self.tmp_output_file = output_file.replace(".json", "_tmp.pkl")
# Build a dict of {task_name -> metric configuration} for quick lookup self.scoring_functions = {} for task_name, task_samples in self.hf_data.items(): self.scoring_functions[task_name] = ast.literal_eval( task_samples[0]["metric_info"] )
def _load_hf(self, subset_name: str) -> List[Dict[str, Any]]: """ Load the HF dataset for the given subset name. """ from datasets import load_dataset dataset = load_dataset("TIGER-Lab/MEGA-Bench", subset_name)["test"] task_dict = {} for sample in dataset: task_name = sample["task_name"] if task_name not in task_dict: task_dict[task_name] = [] task_dict[task_name].append(sample)
return task_dict
def _get_eval_context(self, task_name, query): if "query_idx" in query: query_idx = query["query_idx"] eval_context = self.hf_data[task_name][query_idx]["eval_context"] else: global_idx = query["global_idx"] global_idx_to_sample = {sample["id"]: sample for sample in self.hf_data[task_name]} eval_context = global_idx_to_sample[global_idx]["eval_context"]
eval_context = ast.literal_eval(eval_context) return eval_context def _determine_eval_style(self, task): metric_info = self.scoring_functions[task["task_name"]] all_task_metrics = list(metric_info["field_score_function"].values()) eval_type = ( "rule" if ( "gpt_4o_as_judge" not in all_task_metrics and "ascii_art_gpt4o_judge" not in all_task_metrics ) else "llm" ) return eval_type
def evaluate(self): """ The main entry point to evaluate all tasks in self.data based on the HF dataset’s metric info. """ if os.path.exists(self.tmp_output_file): exist_records = load(self.tmp_output_file) else: exist_records = {} num_tasks = 0 num_queries = 0 total_query_score = 0.0 total_task_score = 0.0
# Evaluate each task for task in self.data: task_name = task.get("task_name", "") if task_name not in exist_records: exist_records[task_name] = {}
# If no scoring config is found for the given task_name, skip score_config = self.scoring_functions.get( task_name, { "field_score_function": {}, "aggregation": {"function": None, "field_weights": {}}, "response_parse_function": None, }, ) if not task.get("query_response"): # No queries to score continue
num_tasks += 1 task_score_sum = 0.0 # Prepare the aggregator aggregator = AggregationType.from_string(score_config["aggregation"]["function"]) field_weights = score_config["aggregation"]["field_weights"]
# Parse the metric definitions field_score_functions = score_config.get("field_score_function", {}) global_aux_metrics = score_config.get("global_aux_metrics", {}) parser_type_str = score_config.get("response_parse_function", "dummy") parser = ResponseParseType.from_string(parser_type_str)
# Extract the fields from the first correct_answer (assuming uniform) first_correct = task["query_response"][0]["correct_answer"] all_fields = list(first_correct.keys()) # Usually, we only treat “##something” fields as metadata, so skip them: answer_fields = [f for f in all_fields if not f.startswith("##")]
# For each query in the task for idx, query in enumerate(task["query_response"]): num_queries += 1 response_text = query.get("response", "") correct_answer = query["correct_answer"]
# 1) Parse the response according to the specified parser response_obj = self._parse_response( task_name, parser, response_text, correct_answer, answer_fields, query, task, )
if idx in exist_records[task_name]: query["scores"] = exist_records[task_name][idx] else: # Initialize scores for this query query["scores"] = {"field": {}, "info": {}}
# 2) Evaluate each field for fld, fld_metric_name in field_score_functions.items(): metric = self._build_metric(fld_metric_name, score_config) self._evaluate_field( task_name, metric, fld, response_obj, correct_answer, query )
# Evaluate global auxiliary metrics (if any) for fld, fld_metric_name in global_aux_metrics.items(): metric = self._build_metric(fld_metric_name, score_config) # Some tasks want the entire response object to do an additional check # So, pass original `response_obj` under `fld` key: tmp_obj = {fld: response_obj} self._evaluate_field( task_name, metric, fld, tmp_obj, correct_answer, query, is_aux=True, )
exist_records[task_name][idx] = query["scores"] if idx % 10 == 0 or idx == len(task["query_response"]) - 1: dump(exist_records, self.tmp_output_file)
# 3) Aggregate the query-level score query["scores"]["query"] = aggregator.aggregate( query["scores"]["field"], field_weights, )
if query["scores"]["query"] >= 0: task_score_sum += query["scores"]["query"]
# Calculate overall task score if task["query_response"]: mean_score = task_score_sum / len(task["query_response"]) else: mean_score = 0.0 task["task_score"] = task_score_sum task["mean_task_score"] = mean_score task["eval_type"] = self._determine_eval_style(task)
total_query_score += task_score_sum total_task_score += mean_score
print(f"[Task: {task_name}] Score = {task_score_sum} / {len(task['query_response'])}")
# Produce overall summary stats summary = {} if num_tasks > 0: macro_mean_score = total_task_score / num_tasks summary["macro_mean_score"] = macro_mean_score else: summary["macro_mean_score"] = 0.0
if num_queries > 0: micro_mean_score = total_query_score / num_queries summary["micro_mean_score"] = micro_mean_score else: summary["micro_mean_score"] = 0.0
summary["num_tasks"] = num_tasks summary["num_queries"] = num_queries # print(f"\n=== Evaluation Summary ===\n{json.dumps(summary, indent=4)}\n")
# Write back final data + summary output_data = { "data": self.data, "summary": summary, } self._save_results(self.output_file, output_data) print(f"Evaluation complete! Results saved to {self.output_file}")
def _evaluate_field( self, task_name: str, metric: Any, field: str, response_obj: Dict[str, Any], correct_answer: Dict[str, Any], query: Dict[str, Any], is_aux: bool = False, ) -> float: """Compute score for a single field using the given metric.""" eval_context = self._get_eval_context(task_name, query)
if metric == MetricType.UNSUPPORTED: print(f"The metric for {field} in task {task_name} is not supported") return 0.0 elif metric == MetricType.SYMBOLIC_PLANNING_TEST or metric == MetricType.PROGRAM_JUDGE: query["scores"]["field"][field] = metric.match( response_obj.get(field), eval_context, ) elif metric == MetricType.CONSTRAINED_GENERATION: score, eval_info = metric.match(response_obj, eval_context) query["scores"]["field"][field] = score query["scores"]["info"][field] = eval_info elif metric == MetricType.XML_NORM_POINT_IN_BBOX: score, eval_info = metric.match(response_obj.get(field), eval_context) query["scores"]["field"][field] = score query["scores"]["info"][field] = eval_info elif isinstance(metric, MetricType.VLM_AS_JUDGE.class_impl): images = query.get("images", []) question = query.get("question", "") correct_val = correct_answer.get(field, "") if not is_aux else correct_answer response_info = ( response_obj.get(field) if isinstance(response_obj, dict) else response_obj ) query["scores"]["field"][field] = metric.match( response_info, correct_val, images=images, question=question, eval_context=eval_context, ) else: correct_val = correct_answer.get(field, "") if not is_aux else correct_answer correct_val = evaluate_as_string(correct_val) # remove extra formatting predicted_val = response_obj.get(field, "") query["scores"]["field"][field] = metric.match(predicted_val, correct_val)
def _parse_response( self, task_name: str, parser, response_text: str, correct_answer: Dict[str, Any], answer_fields: List[str], query: Dict[str, Any], task: Dict[str, Any], ) -> Dict[str, Any]: """ Parse the raw response into a structured object, depending on the parser. """ res_parsing_pass = True if parser.is_single_field_parser(): # single field assert ( len(answer_fields) == 1 ), "The answer_string parse must be used when the answer has a single field" answer_key = answer_fields[0]
global_description = task["task_description"] query_question = query["question"] is_single_line_ans = "\n" not in correct_answer[answer_key]
response_obj = parser.parse( response_text, answer_key, global_description=global_description, query_question=query_question, is_single_line_ans=is_single_line_ans, ) assert isinstance(response_obj[answer_key], str), "Single-field parsing results must be string" else: # Structural output (using JSON parser or other specified parsing func) or dummy parse (return all) response_obj = parser.parse(response_text)
if parser == ResponseParseType.JSON and ( not isinstance(response_obj, dict) or not response_obj ): # Expect a JSON, but parsing failed, # Record the failure parsing, and use the raw string for each field of the answer res_parsing_pass = False response_obj = {} for field in correct_answer: response_obj[field] = response_text
if not res_parsing_pass: print( f"Task:{task_name}, cannot parse query with global idx {query['global_idx']}" ) return response_obj
def _build_metric(self, metric_name: str, score_config: Dict[str, Any]): """ Given a string for the metric (e.g. 'gpt_4o_as_judge'), return the actual MetricType or a specialized metric class. """ metric = MetricType.from_string(metric_name) if metric == MetricType.VLM_AS_JUDGE: # Build the GPT4O metric using the provided config gpt4o_configs = score_config.get("gpt4o_eval_configs", {}) metric = metric.class_impl(gpt4o_configs) elif metric == MetricType.ASCII_ART_GPT4O_JUDGE: # Build the ASCII Art metric using the provided config ascii_art_configs = score_config.get("ascii_art_eval_configs", {}) metric = metric.class_impl(ascii_art_configs) return metric
@staticmethod def _load_json(file_path: str) -> Any: with open(file_path, "r", encoding="utf-8") as f: return json.load(f)
@staticmethod def _save_results(file_path: str, data: Any) -> None: """ Safe-write a JSON file via temp file + replace. Since the results file is long, this avoid breaking the file in case of a crash. """ temp_filename = f"{file_path}.tmp" with open(temp_filename, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=4) os.replace(temp_filename, file_path)
def main(): parser = argparse.ArgumentParser(description="Simple Evaluator") parser.add_argument( "--subset_name", type=str, required=True, help="The subset of MEGA-Bench to evaluate.", ) parser.add_argument( "--submission_file", type=str, required=True, help="Path to a JSON file containing model responses.", ) parser.add_argument( "--output_file", type=str, required=True, help="Where to store the evaluation results (JSON).", )
args = parser.parse_args() evaluator = MEGABenchEvaluator( subset_name=args.subset_name, responses_file=args.submission_file, output_file=args.output_file, ) evaluator.evaluate()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259from functools import cached_propertyfrom enum import Enumfrom .utils import lazy_importimport logging
class MetricType(Enum): """The types of metrics."""
EXACT_STR_MATCH = "exact_str_match" SIMPLE_STR_MATCH = "simple_str_match" CODE_RESULT_EXACT_STR_MATCH = "code_result_exact_str_match" DICT_EXACT_STR_MATCH_AGG_RECALL = "dict_exact_str_match_agg_recall" EXACT_STR_MATCH_CASE_INSENSITIVE = "exact_str_match_case_insensitive" NORM_SIM_DAMERAU_LEVENSHTEIN = "normalized_similarity_damerau_levenshtein" NEAR_STR_MATCH = "near_str_match" NUMBER_RELATIVE_DIFF_RATIO = "number_rel_diff_ratio" SET_EQUALITY = "set_equality" SET_EQUALITY_CASE_INSENSITIVE = "set_equality_case_insensitive" DICT_SET_EQUALITY_AGG_JACCARD = "dict_set_equality_agg_jaccard" DICT_PRECISION = "dict_precision" JACCARD_INDEX = "jaccard_index" JACCARD_INDEX_CASE_INSENSITIVE = "jaccard_index_case_insensitive" DICT_JACCARD_AGG_JACCARD = "dict_jaccard_agg_jaccard" DICT_EQUALITY = "dict_equality" SET_PRECISION = "set_precision" POSITIVE_INT_MATCH = "positive_int_match" CHESS_MOVE_LIST_JACCARD_INDEX = "chess_move_list_jaccard_index" LONGEST_COMMON_LIST_PREFIX_RATIO = "longest_common_list_prefix_ratio" ASCII_ART_GPT4O_JUDGE = "ascii_art_gpt4o_judge" NLI_ENTAILMENT = "nli_entailment" BLEU = "bleu" GLEU_CN = "gleu_cn" XML_NORM_BBOX_IOU_SINGLE = "xml_nbbox_iou_single" LATEX_EXPR_EQUALITY = "latex_expr_equality" TEXT_WITH_LATEX_EXPR_EQUALITY = "text_with_latex_expr_equality" NORM_BBOX_IOU_TUPLE = "nbbox_iou_tuple" NORM_BBOX_IOU_SINGLE = "nbbox_iou_single" NORM_BBOX_IOU_SEQUENCE = "nbbox_iou_sequence" DICT_NORM_BBOX_IOU_TUPLE_AGG_JACCARD = "dict_nbbox_iou_tuple_agg_jaccard" XML_NORM_POINT_IN_BBOX = "xml_norm_point_in_bbox" XML_NORM_POINT_DISTANCE = "xml_norm_point_distance" GEO_PROXIMITY_LOCATION_DICT = "geo_proximity_location_dict" NORMALIZED_RMSE = "normalized_rmse" PROGRAM_JUDGE = "program_judge" STR_SET_EQUALITY_LINE_BREAK = "str_set_equality_line_break" STR_SET_EQUALITY_COMMA = "str_set_equality_comma" SEQUENCE_EQUALITY = "sequence_equality" SEQUENCE_EQUALITY_CASE_INSENSITIVE = "sequence_equality_case_insensitive" SEQUENCE_ACCURACY_CASE_INSENSITIVE = "sequence_accuracy_case_insensitive" ANGLE_SEQ_FLOAT_RMSE = "angle_seq_float_rmse" SYMBOLIC_PLANNING_TEST = "symbolic_planning_test" MULTI_REF_PHRASE_EVAL = "multi_ref_phrase" GENERAL_SINGLE_NUMERICAL_MATCH = "general_single_numerical_match" BOXED_SINGLE_NUMERICAL_MATCH = "boxed_single_numerical_match" SEQUENCE_COORDS_SIMILARITY = "sequence_coords_similarity" CONSTRAINED_GENERATION = "constrained_generation" VLM_AS_JUDGE = "gpt_4o_as_judge" UNSUPPORTED = "unsupported"
@cached_property def class_impl(self): lazy_imports = { MetricType.SIMPLE_STR_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.simple_str_match", "SimpleStrMatch" ), MetricType.EXACT_STR_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.exact_str_match", "ExactStrMatch" ), MetricType.CODE_RESULT_EXACT_STR_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.exact_str_match", "CodeResultExactStrMatch" ), MetricType.DICT_EXACT_STR_MATCH_AGG_RECALL: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_exact_match_agg_recall", "DictExactStrMatchAggRecall", ), MetricType.EXACT_STR_MATCH_CASE_INSENSITIVE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.exact_str_match_case_insensitive", "ExactStrMatchCaseInsensitive", ), MetricType.NORM_SIM_DAMERAU_LEVENSHTEIN: lazy_import( "vlmeval.dataset.utils.megabench.scoring.normalized_similarity_damerau_levenshtein", "NormalizedSimilarityDamerauLevenshtein", ), MetricType.NEAR_STR_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.near_str_match", "NearStrMatch" ), MetricType.NUMBER_RELATIVE_DIFF_RATIO: lazy_import( "vlmeval.dataset.utils.megabench.scoring.number_rel_diff_ratio", "NumberRelDiffRatio" ), MetricType.SET_EQUALITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.set_equality", "SetEquality" ), MetricType.SET_EQUALITY_CASE_INSENSITIVE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.set_equality", "SetEqualityCaseInsensitive" ), MetricType.DICT_SET_EQUALITY_AGG_JACCARD: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_set_equality_agg_jaccard", "DictSetEqualityAggJaccard", ), MetricType.DICT_EQUALITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_equality", "DictEquality", ), MetricType.DICT_PRECISION: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_equality", "DictPrecision", ), MetricType.JACCARD_INDEX: lazy_import("vlmeval.dataset.utils.megabench.scoring.jaccard", "Jaccard"), MetricType.JACCARD_INDEX_CASE_INSENSITIVE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.jaccard", "JaccardCaseInsensitive" ), MetricType.DICT_JACCARD_AGG_JACCARD: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_jaccard_agg_jaccard", "DictJaccardAggJaccard" ), MetricType.SET_PRECISION: lazy_import( "vlmeval.dataset.utils.megabench.scoring.set_precision", "SetPrecision" ), MetricType.POSITIVE_INT_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.positive_int_match", "PositiveIntMatch" ), MetricType.CHESS_MOVE_LIST_JACCARD_INDEX: lazy_import( "vlmeval.dataset.utils.megabench.scoring.chess_jaccard", "ChessMoveJaccard" ), MetricType.LONGEST_COMMON_LIST_PREFIX_RATIO: lazy_import( "vlmeval.dataset.utils.megabench.scoring.longest_common_list_prefix_ratio", "LongestCommonListPrefixRatio", ), MetricType.ASCII_ART_GPT4O_JUDGE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.ascii_art_gpt4o_judge", "AsciiArtVLMJudgeScore", ), MetricType.NLI_ENTAILMENT: lazy_import( "vlmeval.dataset.utils.megabench.scoring.nli_entailment", "NliEntailment" ), MetricType.BLEU: lazy_import( "vlmeval.dataset.utils.megabench.scoring.sacrebleu_bleu", "Bleu", ), MetricType.GLEU_CN: lazy_import( "vlmeval.dataset.utils.megabench.scoring.gleu", "GLEUChinese", ), MetricType.XML_NORM_BBOX_IOU_SINGLE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.xml_nbbox_iou", "XmlNbboxIouSingle" ), MetricType.BOXED_SINGLE_NUMERICAL_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.general_numerical_match", "BoxedSingleNumericalMatch" ), MetricType.GENERAL_SINGLE_NUMERICAL_MATCH: lazy_import( "vlmeval.dataset.utils.megabench.scoring.general_numerical_match", "GeneralSingleNumericalMatch" ), MetricType.SEQUENCE_COORDS_SIMILARITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.coordinate_sequence_match", "CoordsSequenceSimilarity" ), MetricType.LATEX_EXPR_EQUALITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.latex_expr_equality", "LatexExprEquality", ), MetricType.TEXT_WITH_LATEX_EXPR_EQUALITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.latex_expr_equality", "TextLatexExprEquality", ), MetricType.NORM_BBOX_IOU_TUPLE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.nbbox_iou", "NbboxIouTuple" ), MetricType.NORM_BBOX_IOU_SINGLE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.nbbox_iou", "NbboxIouSingle" ), MetricType.NORM_BBOX_IOU_SEQUENCE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.nbbox_iou", "NbboxIouSequence" ), MetricType.DICT_NORM_BBOX_IOU_TUPLE_AGG_JACCARD: lazy_import( "vlmeval.dataset.utils.megabench.scoring.dict_nbbox_iou_tuple_agg_jaccard", "DictNbboxIouTupleAggJaccard", ), MetricType.XML_NORM_POINT_IN_BBOX: lazy_import( "vlmeval.dataset.utils.megabench.scoring.xml_norm_point_in_bbox", "XmlNormPointInBbox", ), MetricType.XML_NORM_POINT_DISTANCE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.xml_norm_point_distance", "XmlNormPointDistance", ), MetricType.GEO_PROXIMITY_LOCATION_DICT: lazy_import( "vlmeval.dataset.utils.megabench.scoring.geo_proximity", "GeoProximityLocationDict" ), MetricType.NORMALIZED_RMSE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.mse", "NormalizedRMSE" ), MetricType.PROGRAM_JUDGE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.program_judge", "ProgramJudge" ), MetricType.STR_SET_EQUALITY_LINE_BREAK: lazy_import( "vlmeval.dataset.utils.megabench.scoring.set_equality", "StringSetEqualityLineSplit" ), MetricType.STR_SET_EQUALITY_COMMA: lazy_import( "vlmeval.dataset.utils.megabench.scoring.set_equality", "StringSetEqualityCommaSplit" ), MetricType.SEQUENCE_EQUALITY: lazy_import( "vlmeval.dataset.utils.megabench.scoring.sequence_equality", "SequenceEquality" ), MetricType.SEQUENCE_EQUALITY_CASE_INSENSITIVE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.sequence_equality", "SequenceEqualityCaseInsensitive" ), MetricType.SEQUENCE_ACCURACY_CASE_INSENSITIVE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.sequence_equality", "SequenceAccuracyCaseInsensitive" ), MetricType.ANGLE_SEQ_FLOAT_RMSE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.mse", "AngleSeqFloatRMSE" ), MetricType.SYMBOLIC_PLANNING_TEST: lazy_import( "vlmeval.dataset.utils.megabench.scoring.symbolic_planning", "SymbolicPlanningMetricTest" ), MetricType.MULTI_REF_PHRASE_EVAL: lazy_import( "vlmeval.dataset.utils.megabench.scoring.multi_ref_phrase", "MultipleReferencePhraseEval" ), MetricType.CONSTRAINED_GENERATION: lazy_import( "vlmeval.dataset.utils.megabench.scoring.constrained_generation", "ConstrainedGenerationEval" ), MetricType.VLM_AS_JUDGE: lazy_import( "vlmeval.dataset.utils.megabench.scoring.vlm_as_judge", "VLMJudgeScore" ), }
if self not in lazy_imports: logging.error(f"Metric {self} not implemented...")
importer = lazy_imports.get( self, lazy_import("vlmeval.dataset.utils.megabench.scoring.unsupported_scoring", "UnsupportedScoring"), ) return importer()
def match(self, response: str, correct_answer: str, task_info=None): if not task_info: return self.class_impl.match(response, correct_answer) else: return self.class_impl.match(response, correct_answer, task_info)
@classmethod def from_string(cls, s): try: if s is None: return cls("unsupported") return cls(s.lower()) except KeyError as exc: raise ValueError(f"Invalid metric type: {s}") from exc
@classmethod def get_all_values(cls): return list(cls)
# List all of the supported metrics:if __name__ == "__main__": print("All MetricType values:") for metric_type in MetricType.get_all_values(): print(f"{metric_type.name}: {metric_type.value}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import loggingfrom .common.parsers import parse_jsonfrom .common.utils import ( extract_code_block_content, extract_answer_content, evaluate_as_string, drop_additional_text,)
logger = logging.getLogger("errorLogger")
class AnswerStrParse: """Parse the response for the single answer field."""
@classmethod def _parse( cls, response: str, *, is_ascii_art: bool = False, should_remove_surrounding_whitespace=True, global_description: str = "", query_question: str = "", is_single_line_ans: bool = None, ) -> dict: """Try to parse a single answer.""" if response is None: response = ""
# Extract the answer content based on "Answer: ..." format answer_content = extract_answer_content( response, is_ascii_art=is_ascii_art, should_remove_surrounding_whitespace=should_remove_surrounding_whitespace, )
# Extract things from the code block if response is wrapped by a code block answer_content, is_code = extract_code_block_content( answer_content, is_ascii_art=is_ascii_art, should_remove_surrounding_whitespace=should_remove_surrounding_whitespace, )
if not is_code and is_single_line_ans and not is_ascii_art: answer_content = drop_additional_text(answer_content)
# Check if the content is a potential dict or list. if answer_content.startswith("{") or answer_content.startswith("["): # Attempt to parse the content as JSON response_obj = parse_json(answer_content) if response_obj == {}: if "{}" not in answer_content: return answer_content elif response_obj == []: # logger.error( # f"Unexpected answer parsing error:\n{response=}\n{global_description=}\n{query_question=}\n{is_ascii_art=}" # ) if "[]" not in answer_content: return answer_content return str(response_obj) # make sure the response to the metric is always a string else: # drop the redundant string quotes answer_content = evaluate_as_string(answer_content) return answer_content
@classmethod def parse( cls, response: str, answer_key: str, *, global_description: str = "", query_question: str = "", is_single_line_ans: bool = None, ) -> dict: """Try to parse a single answer.""" response_parsed = cls._parse( response, is_ascii_art=False, global_description=global_description, query_question=query_question, is_single_line_ans=is_single_line_ans, ) results = {answer_key: response_parsed} return results
class AsciiAnswerStrParse(AnswerStrParse): """Parse the response for the single ASCII answer field."""
@classmethod def parse( cls, response: str, answer_key: str, *, global_description: str = "", query_question: str = "", is_single_line_ans: bool = None, ) -> dict: """Try to parse a single answer.""" response_parsed = cls._parse( response, is_ascii_art=True, global_description=global_description, query_question=query_question, is_single_line_ans=is_single_line_ans, ) results = {answer_key: response_parsed} return results
class VerbatimAnswerStrParse(AnswerStrParse): """Parse the response for a single answer field that should not have preceding or trailing whitespace removed."""
@classmethod def parse( cls, response: str, answer_key: str, *, global_description: str = "", query_question: str = "", is_single_line_ans: bool = None, ) -> dict: """Try to parse a single answer.""" response_parsed = cls._parse( response, is_ascii_art=True, should_remove_surrounding_whitespace=False, global_description=global_description, query_question=query_question, is_single_line_ans=is_single_line_ans, ) results = {answer_key: response_parsed} return results123456class DummyParse:
@staticmethod def parse(response: str, *args, **kwargs) -> dict: """return the raw string without doing anything""" return response.strip()1234567891011121314151617from .common.parsers import parse_jsonfrom .common.utils import evaluate_as_string
class JsonParse: """Load the response as a JSON object."""
@staticmethod def parse(response: str): """Parse the JSON object, including nested JSON strings.""" parsed_res = parse_json(response) # Drop the potentially duplicated string quotes if isinstance(parsed_res, dict): for key, val in parsed_res.items(): parsed_res[key] = evaluate_as_string(val)
return parsed_res123456789101112131415antlr4-python3-runtime==4.11.0filelock==3.16.1geopy==2.4.1jieba==0.42.1nltk==3.9.1numpy==1.26.4pronouncing==0.2.0rapidfuzz==3.9.5regex==2024.7.24requests==2.32.3requests_cache==1.2.1sacrebleu==2.4.3sympy==1.13.2tqdm==4.66.4Unidecode==1.3.8123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from functools import cached_propertyfrom enum import Enumfrom .parsing.json_parse import JsonParsefrom .parsing.answer_str_parse import ( AnswerStrParse, AsciiAnswerStrParse, VerbatimAnswerStrParse,)from vlmeval.dataset.utils.megabench.parsing.dummy_parse import DummyParse
class ResponseParseType(Enum): """Parse the response."""
JSON = "json" ANSWER_STR = "answer_string" ASCII_ANSWER_STR = "ascii_answer_string" VERBATIM_ANSWER_STR = "verbatim_answer_string" DUMMY = "dummy" UNSUPPORTED = "unsupported"
@cached_property def class_impl(self): if self == ResponseParseType.ANSWER_STR: return AnswerStrParse elif self == ResponseParseType.ASCII_ANSWER_STR: return AsciiAnswerStrParse elif self == ResponseParseType.VERBATIM_ANSWER_STR: return VerbatimAnswerStrParse elif self == ResponseParseType.DUMMY: return DummyParse else: return JsonParse
def is_single_field_parser(self): return self in [ ResponseParseType.ANSWER_STR, ResponseParseType.ASCII_ANSWER_STR, ResponseParseType.VERBATIM_ANSWER_STR, ]
def parse(self, response: str, *args, **kwargs): """Parse the response.""" return self.class_impl.parse(response, *args, **kwargs)
@staticmethod def from_string(s): """Initialize the response parsing type from a string.""" try: if s is None: return ResponseParseType("unsupported") return ResponseParseType(s.lower()) except KeyError as exc: raise ValueError(f"Invalid metric type: {s}") from exc1234567891011121314151617181920import torchfrom transformers import pipeline
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")pipe = pipeline( "text-classification", model="microsoft/deberta-large-mnli", device=device)
class NliEntailment: """NLI entailment, where the correct answer is used as the premise."""
@staticmethod def match(response, correct_answer) -> int: """Return whether the response and correct answer agree with each other.""" if not isinstance(response, str) or isinstance(correct_answer, str): return 0 resp = pipe(f"[CLS] {correct_answer.strip()} [SEP] {response.strip()} [SEP]") return 1 if resp[0]["label"] == "ENTAILMENT" else 0Shapegrid/ShapeGrid_dis.parquetAdded+3
Shapegrid/ShapeGrid_loc.parquetAdded+3
VLMEvalKit-sudoku/.github/scripts/assert_score.pyAdded+61
VLMEvalKit-sudoku/.github/workflows/lint.ymlAdded+23
VLMEvalKit-sudoku/.github/workflows/pr-run-test.ymlAdded+70
VLMEvalKit-sudoku/llava/serve/__init__.pyAdded
VLMEvalKit-sudoku/llava/serve/examples/extreme_ironing.jpgAdded

Large File Pointer Details
- SHA256: a54caa21bc513ed25c8ca7f5747555c05dfd4e33f6a3cf5c08b3d9138a4da1d9
- Pointer size: 130 Bytes
- Size of remote file: 62.6 kB
VLMEvalKit-sudoku/llava/train/train_dpo.pyAdded+1782
VLMEvalKit-sudoku/requirements/docs.txtAdded+11
VLMEvalKit-sudoku/vlmeval/api/__pycache__/claude.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/gemini.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/glm_vision.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/hf_chat_model.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/hunyuan.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/lmdeploy.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/api/__pycache__/qwen_vl_api.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/megabench.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/__pycache__/sfebench.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/cmmmu.pyAdded+354
VLMEvalKit-sudoku/vlmeval/dataset/creation.pyAdded+741
VLMEvalKit-sudoku/vlmeval/dataset/dude.pyAdded+211
VLMEvalKit-sudoku/vlmeval/dataset/image_mcq.pyAdded
VLMEvalKit-sudoku/vlmeval/dataset/m4bench.pyAdded+193
VLMEvalKit-sudoku/vlmeval/dataset/miabench.pyAdded+166
VLMEvalKit-sudoku/vlmeval/dataset/mmbench_video.pyAdded+257
VLMEvalKit-sudoku/vlmeval/dataset/mmifeval.pyAdded+483
VLMEvalKit-sudoku/vlmeval/dataset/qbench_video.pyAdded+354
VLMEvalKit-sudoku/vlmeval/dataset/text_base.pyAdded+88
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/mlvu.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/multiple_choice.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/omni_verifier.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/shortqa.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/spatial457.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/tamperbench.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/tempcompass.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/__pycache__/yorn.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/README.mdAdded+51
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__init__.pyAdded+5
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__pycache__/evaluator.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/__pycache__/response_parse_type.cpython-310.pycAdded
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/aggregation/min_agg.pyAdded+14
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/aggregation_type.pyAdded+25
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/evaluator.pyAdded+399
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/metric_type.pyAdded+259
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/answer_str_parse.pyAdded+137
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/dummy_parse.pyAdded+6
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/parsing/json_parse.pyAdded+17
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/requirements.txtAdded+15
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/response_parse_type.pyAdded+54
VLMEvalKit-sudoku/vlmeval/dataset/utils/megabench/scoring/nli_entailment.pyAdded+20