diff --git a/lmms-eval-0.2.0.post1/.github/issue_template.md b/lmms-eval-0.2.0.post1/.github/issue_template.md
deleted file mode 100644
index dc925b3fd043385737ce1f5671848d107f431f72..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/.github/issue_template.md
+++ /dev/null
@@ -1,8 +0,0 @@
-Before you open an issue, please check if a similar issue already exists or has been closed before.
-
-### When you open an issue, please be sure to include the following
-
-- [ ] A descriptive title: [xxx] XXXX
-- [ ] A detailed description
-
-Thank you for your contributions!
diff --git a/lmms-eval-0.2.0.post1/.github/pull_request_template.md b/lmms-eval-0.2.0.post1/.github/pull_request_template.md
deleted file mode 100644
index 5c80b1fa20de9d1888d22d83ba0a0a0b6331ddc0..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/.github/pull_request_template.md
+++ /dev/null
@@ -1,8 +0,0 @@
-Before you open a pull-request, please check if a similar issue already exists or has been closed before.
-
-### When you open a pull-request, please be sure to include the following
-
-- [ ] A descriptive title: [xxx] XXXX
-- [ ] A detailed description
-
-Thank you for your contributions!
diff --git a/lmms-eval-0.2.0.post1/.github/workflows/black.yml b/lmms-eval-0.2.0.post1/.github/workflows/black.yml
deleted file mode 100644
index 11721fd8caf8deb5a7ab3ba9961deabcbe4632a2..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/.github/workflows/black.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-name: Lint
-
-on: [push, pull_request]
-
-jobs:
- lint:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
- - name: Set up Python
- uses: actions/setup-python@v4
- with:
- python-version: '3.9'
- - name: Install specific version of Black
- run: pip install black==23.9.1
- - name: Run Black
- run: black --line-length=240 ./
\ No newline at end of file
diff --git a/lmms-eval-0.2.0.post1/.gitignore b/lmms-eval-0.2.0.post1/.gitignore
deleted file mode 100644
index 2557ab1bd2d7c9164b9f2cf73e41930c4759b77f..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/.gitignore
+++ /dev/null
@@ -1,39 +0,0 @@
-env
-*.pyc
-output/
-data/
-lm_cache
-.idea
-build
-dist
-*.egg-info
-venv
-.vscode/
-temp
-__pycache__
-.ipynb_checkpoints
-temp
-# IPython
-profile_default/
-ipython_config.py
-logs/
-scripts/
-wandb/
-SimSun.ttf
-submissions/
-lmms_eval/tasks/hallusion_bench/hallusion_output_vs_model.json
-lmms_eval/tasks/hallusion_bench/hallusion_output_vd_model.json
-zk.log
-cache_dir
-ckpt
-pretrained/
-LLaVA/
-*logs
-temp/
-InternVL/
-logs/
-data/
-llava-video/
-Video-MME/
-VATEX/
-lmms_eval/tasks/vatex/__pycache__/utils.cpython-310.pyc
diff --git a/lmms-eval-0.2.0.post1/.pre-commit-config.yaml b/lmms-eval-0.2.0.post1/.pre-commit-config.yaml
deleted file mode 100644
index a33bcacfabaac9ecc6a6deaaad42553f41946ee3..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/.pre-commit-config.yaml
+++ /dev/null
@@ -1,6 +0,0 @@
-repos:
- - repo: https://github.com/psf/black
- rev: 23.12.1
- hooks:
- - id: black
- language_version: python3
\ No newline at end of file
diff --git a/lmms-eval-0.2.0.post1/LICENSE b/lmms-eval-0.2.0.post1/LICENSE
deleted file mode 100644
index aa318e268e9e102fb214d2ceab0a8a3de1c63ab9..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/LICENSE
+++ /dev/null
@@ -1,56 +0,0 @@
-# For the main pipeline structure-related code, we maintain the original license provided with lm-evaluation-harness, which is the MIT License.
-
-MIT License
-
-Copyright (c) 2024 LMMs-Lab
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-# For the multimodal models and datasets that we have added (defined as code in the lmms_eval/tasks and lmms_eval/models folders), we apply the Apache License.
-
-Apache 2.0 License
-
-Copyright (c) 2024 LMMs-Lab
-
-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.
-
-When modifying the code, please include the following information about the original lmms-eval source:
-# Adopted from lmms-eval from https://github.com/EvolvingLMMs-Lab/lmms-eval. Below is the original copyright:
-#
-# 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.
diff --git a/lmms-eval-0.2.0.post1/README.md b/lmms-eval-0.2.0.post1/README.md
deleted file mode 100644
index 2bf7a26e363025b1fd3e046d917775fc0421fb09..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/README.md
+++ /dev/null
@@ -1,258 +0,0 @@
-
-
-
-
-# The Evaluation Suite of Large Multimodal Models
-
-> Accelerating the development of large multimodal models (LMMs) with `lmms-eval`
-
-🏠 [LMMs-Lab Homepage](https://lmms-lab.github.io/) | 🎉 [Blog](https://lmms-lab.github.io/lmms-eval-blog/lmms-eval-0.1/) | 📚 [Documentation](docs/README.md) | 🤗 [Huggingface Datasets](https://huggingface.co/lmms-lab) |
[discord/lmms-eval](https://discord.gg/zdkwKUqrPy)
-
----
-
-## Annoucement
-
-- [2024-06] 🎬🎬 The `lmms-eval/v0.2` has been upgraded to support video evaluations for video models like LLaVA-NeXT Video and Gemini 1.5 Pro across tasks such as EgoSchema, PerceptionTest, VideoMME, and more. Please refer to the [blog](https://lmms-lab.github.io/posts/lmms-eval-0.2/) for more details
-
-- [2024-03] 📝📝 We have released the first version of `lmms-eval`, please refer to the [blog](https://lmms-lab.github.io/posts/lmms-eval-0.1/) for more details
-
-## Why `lmms-eval`?
-
-
-
-
-
-In today's world, we're on an exciting journey toward creating Artificial General Intelligence (AGI), much like the enthusiasm of the 1960s moon landing. This journey is powered by advanced large language models (LLMs) and large multimodal models (LMMs), which are complex systems capable of understanding, learning, and performing a wide variety of human tasks.
-
-To gauge how advanced these models are, we use a variety of evaluation benchmarks. These benchmarks are tools that help us understand the capabilities of these models, showing us how close we are to achieving AGI.
-
-However, finding and using these benchmarks is a big challenge. The necessary benchmarks and datasets are spread out and hidden in various places like Google Drive, Dropbox, and different school and research lab websites. It feels like we're on a treasure hunt, but the maps are scattered everywhere.
-
-In the field of language models, there has been a valuable precedent set by the work of [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness). They offer integrated data and model interfaces, enabling rapid evaluation of language models and serving as the backend support framework for the [open-llm-leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), and has gradually become the underlying ecosystem of the era of foundation models.
-
-We humbly obsorbed the exquisite and efficient design of [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) and introduce **lmms-eval**, an evaluation framework meticulously crafted for consistent and efficient evaluation of LMM.
-
-## Installation
-
-For formal usage, you can install the package from PyPI by running the following command:
-```bash
-pip install lmms-eval
-```
-
-For development, you can install the package by cloning the repository and running the following command:
-```bash
-git clone https://github.com/EvolvingLMMs-Lab/lmms-eval
-cd lmms-eval
-pip install -e .
-```
-
-If you wanted to test llava, you will have to clone their repo from [LLaVA](https://github.com/haotian-liu/LLaVA) and
-```bash
-# for llava 1.5
-# git clone https://github.com/haotian-liu/LLaVA
-# cd LLaVA
-# pip install -e .
-
-# for llava-next (1.6)
-git clone https://github.com/LLaVA-VL/LLaVA-NeXT
-cd LLaVA-NeXT
-pip install -e .
-```
-
-
-Reproduction of LLaVA-1.5's paper results
-
-You can check the [environment install script](miscs/repr_scripts.sh) and [torch environment info](miscs/repr_torch_envs.txt) to **reproduce LLaVA-1.5's paper results**. We found torch/cuda versions difference would cause small variations in the results, we provide the [results check](miscs/llava_result_check.md) with different environments.
-
-
-
-If you want to test on caption dataset such as `coco`, `refcoco`, and `nocaps`, you will need to have `java==1.8.0 ` to let pycocoeval api to work. If you don't have it, you can install by using conda
-```
-conda install openjdk=8
-```
-you can then check your java version by `java -version`
-
-
-
-Comprehensive Evaluation Results of LLaVA Family Models
-
-
-As demonstrated by the extensive table below, we aim to provide detailed information for readers to understand the datasets included in lmms-eval and some specific details about these datasets (we remain grateful for any corrections readers may have during our evaluation process).
-
-We provide a Google Sheet for the detailed results of the LLaVA series models on different datasets. You can access the sheet [here](https://docs.google.com/spreadsheets/d/1a5ImfdKATDI8T7Cwh6eH-bEsnQFzanFraFUgcS9KHWc/edit?usp=sharing). It's a live sheet, and we are updating it with new results.
-
-
-
-
-
-We also provide the raw data exported from Weights & Biases for the detailed results of the LLaVA series models on different datasets. You can access the raw data [here](https://docs.google.com/spreadsheets/d/1AvaEmuG4csSmXaHjgu4ei1KBMmNNW8wflOD_kkTDdv8/edit?usp=sharing).
-
-
-
-
-
-Our Development will be continuing on the main branch, and we encourage you to give us feedback on what features are desired and how to improve the library further, or ask questions, either in issues or PRs on GitHub.
-
-## Multiple Usages
-
-**Evaluation of LLaVA on MME**
-
-```bash
-python3 -m accelerate.commands.launch \
- --num_processes=8 \
- -m lmms_eval \
- --model llava \
- --model_args pretrained="liuhaotian/llava-v1.5-7b" \
- --tasks mme \
- --batch_size 1 \
- --log_samples \
- --log_samples_suffix llava_v1.5_mme \
- --output_path ./logs/
-```
-
-**Evaluation of LLaVA on multiple datasets**
-
-```bash
-python3 -m accelerate.commands.launch \
- --num_processes=8 \
- -m lmms_eval \
- --model llava \
- --model_args pretrained="liuhaotian/llava-v1.5-7b" \
- --tasks mme,mmbench_en \
- --batch_size 1 \
- --log_samples \
- --log_samples_suffix llava_v1.5_mme_mmbenchen \
- --output_path ./logs/
-```
-
-**For other variants llava. Please change the `conv_template` in the `model_args`**
-
-> `conv_template` is an arg of the init function of llava in `lmms_eval/models/llava.py`, you could find the corresponding value at LLaVA's code, probably in a dict variable `conv_templates` in `llava/conversations.py`
-
-```bash
-python3 -m accelerate.commands.launch \
- --num_processes=8 \
- -m lmms_eval \
- --model llava \
- --model_args pretrained="liuhaotian/llava-v1.6-mistral-7b,conv_template=mistral_instruct" \
- --tasks mme,mmbench_en \
- --batch_size 1 \
- --log_samples \
- --log_samples_suffix llava_v1.5_mme_mmbenchen \
- --output_path ./logs/
-```
-
-**Evaluation of larger lmms (llava-v1.6-34b)**
-
-```bash
-python3 -m accelerate.commands.launch \
- --num_processes=8 \
- -m lmms_eval \
- --model llava \
- --model_args pretrained="liuhaotian/llava-v1.6-34b,conv_template=mistral_direct" \
- --tasks mme,mmbench_en \
- --batch_size 1 \
- --log_samples \
- --log_samples_suffix llava_v1.5_mme_mmbenchen \
- --output_path ./logs/
-```
-
-**Evaluation with a set of configurations, supporting evaluation of multiple models and datasets**
-
-```bash
-python3 -m accelerate.commands.launch --num_processes=8 -m lmms_eval --config ./miscs/example_eval.yaml
-```
-
-**Evaluation with naive model sharding for bigger model (llava-next-72b)**
-
-```bash
-python3 -m lmms_eval \
- --model=llava \
- --model_args=pretrained=lmms-lab/llava-next-72b,conv_template=qwen_1_5,device_map=auto,model_name=llava_qwen \
- --tasks=pope,vizwiz_vqa_val,scienceqa_img \
- --batch_size=1 \
- --log_samples \
- --log_samples_suffix=llava_qwen \
- --output_path="./logs/" \
- --wandb_args=project=lmms-eval,job_type=eval,entity=llava-vl
-```
-
-**Evaluation with SGLang for bigger model (llava-next-72b)**
-
-```bash
-python3 -m lmms_eval \
- --model=llava_sglang \
- --model_args=pretrained=lmms-lab/llava-next-72b,tokenizer=lmms-lab/llavanext-qwen-tokenizer,conv_template=chatml-llava,tp_size=8,parallel=8 \
- --tasks=mme \
- --batch_size=1 \
- --log_samples \
- --log_samples_suffix=llava_qwen \
- --output_path=./logs/ \
- --verbosity=INFO
-```
-
-### Supported models
-
-Please check [supported models](lmms_eval/models/__init__.py) for more details.
-
-### Supported tasks
-
-Please check [supported tasks](lmms_eval/docs/current_tasks.md) for more details.
-
-## Add Customized Model and Dataset
-
-Please refer to our [documentation](docs/README.md).
-
-## Acknowledgement
-
-lmms_eval is a fork of [lm-eval-harness](https://github.com/EleutherAI/lm-evaluation-harness). We recommend you to read through the [docs of lm-eval-harness](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs) for relevant information.
-
----
-
-Below are the changes we made to the original API:
-- Build context now only pass in idx and process image and doc during the model responding phase. This is due to the fact that dataset now contains lots of images and we can't store them in the doc like the original lm-eval-harness other wise the cpu memory would explode.
-- Instance.args (lmms_eval/api/instance.py) now contains a list of images to be inputted to lmms.
-- lm-eval-harness supports all HF language models as single model class. Currently this is not possible of lmms because the input/output format of lmms in HF are not yet unified. Thererfore, we have to create a new class for each lmms model. This is not ideal and we will try to unify them in the future.
-
----
-
-During the initial stage of our project, we thank:
-- [Xiang Yue](https://xiangyue9607.github.io/), [Jingkang Yang](https://jingkang50.github.io/), [Dong Guo](https://www.linkedin.com/in/dongguoset/) and [Sheng Shen](https://sincerass.github.io/) for early discussion and testing.
-
----
-
-During the `v0.1` to `v0.2`, we thank the community support from pull requests (PRs):
-
-> Details are in [lmms-eval/v0.2.0 release notes](https://github.com/EvolvingLMMs-Lab/lmms-eval/releases/tag/untagged-9057ff0e9a72d5a5846f)
-
-**Datasets:**
-
-- VCR: Visual Caption Restoration (officially from the authors, MILA)
-- ConBench (officially from the authors, PKU/Bytedance)
-- MathVerse (officially from the authors, CUHK)
-- MM-UPD (officially from the authors, University of Tokyo)
-- WebSRC (from Hunter Heiden)
-- ScreeSpot (from Hunter Heiden)
-- RealworldQA (from Fanyi Pu, NTU)
-- Multi-lingual LLaVA-W (from Gagan Bhatia, UBC)
-
-**Models:**
-
-- LLaVA-HF (officially from Huggingface)
-- Idefics-2 (from the lmms-lab team)
-- microsoft/Phi-3-Vision (officially from the authors, Microsoft)
-- LLaVA-SGlang (from the lmms-lab team)
-
-## Citations
-
-```shell
-@misc{lmms_eval2024,
- title={LMMs-Eval: Accelerating the Development of Large Multimoal Models},
- url={https://github.com/EvolvingLMMs-Lab/lmms-eval},
- author={Bo Li*, Peiyuan Zhang*, Kaichen Zhang*, Fanyi Pu*, Xinrun Du, Yuhao Dong, Haotian Liu, Yuanhan Zhang, Ge Zhang, Chunyuan Li and Ziwei Liu},
- publisher = {Zenodo},
- version = {v0.1.0},
- month={March},
- year={2024}
-}
-```
diff --git a/lmms-eval-0.2.0.post1/docs/README.md b/lmms-eval-0.2.0.post1/docs/README.md
deleted file mode 100644
index 2c9123632e8acf63f08c72c425fc80401a820067..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/docs/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# LMMs Eval Documentation
-
-Welcome to the docs for `lmms-eval`!
-
-Majority of this documentation is adapted from [lm-eval-harness](https://github.com/EleutherAI/lm-evaluation-harness/)
-
-## Table of Contents
-
-* To learn about the command line flags, see the [commands](commands.md)
-* To learn how to add a new moddel, see the [Model Guide](model_guide.md).
-* For a crash course on adding new tasks to the library, see our [Task Guide](task_guide.md).
-* If you need to upload your datasets into correct HF format with viewer supported, please refer to [tools](https://github.com/EvolvingLMMs-Lab/lmms-eval/tree/pufanyi/hf_dataset_docs/tools)
diff --git a/lmms-eval-0.2.0.post1/docs/commands.md b/lmms-eval-0.2.0.post1/docs/commands.md
deleted file mode 100644
index 4f8c7a7dfbb7c247294ee0b897fe4a864d8c0d84..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/docs/commands.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# User Guide
-This document details the interface exposed by `lmms_eval` and provides details on what flags are available to users.
-
-## Command-line Interface
-
-
-Equivalently, running the library can be done via the `lmms_eval` entrypoint at the command line.
-
-This mode supports a number of command-line arguments, the details of which can be also be seen via running with `-h` or `--help`:
-
-* `--model` : Selects which model type or provider is evaluated. Must be a mdoels registered under lmms_eval/models. For example, `--model qwen_vl` or `--model llava`.
-
-* `--model_args` : Controls parameters passed to the model constructor. Accepts a string containing comma-separated keyword arguments to the model class of the format `"arg1=val1,arg2=val2,..."`, such as, for example `--model_args pretrained=liuhaotian/llava-v1.5-7b,batch_size=1`. For a full list of what keyword arguments, see the initialization of the corresponding model class in `lmms_eval/models/`.
-
-* `--tasks` : Determines which tasks or task groups are evaluated. Accepts a comma-separated list of task names or task group names. Must be solely comprised of valid tasks/groups. You can use `--tasks list` to see all the available tasks. If you add your own tasks but not shown on the list, you can try to set `--verbosity=DEBUG` to view the error message. You can also use `--tasks list_with_num` to check every tasks and the number of question each task contains. However, `list_with_num` will download all the available datasets and may require lots of memory and time.
-
-* `--batch_size` : Sets the batch size used for evaluation. Can be a positive integer or `"auto"` to automatically select the largest batch size that will fit in memory, speeding up evaluation. One can pass `--batch_size auto:N` to re-select the maximum batch size `N` times during evaluation. This can help accelerate evaluation further, since `lm-eval` sorts documents in descending order of context length.
-
-* `--output_path` : A string of the form `dir/file.jsonl` or `dir/`. Provides a path where high-level results will be saved, either into the file named or into the directory named. If `--log_samples` is passed as well, then per-document outputs and metrics will be saved into the directory as well.
-
-* `--log_samples` : If this flag is passed, then the model's outputs, and the text fed into the model, will be saved at per-document granularity. Must be used with `--output_path`.
-
-* `--limit` : Accepts an integer, or a float between 0.0 and 1.0 . If passed, will limit the number of documents to evaluate to the first X documents (if an integer) per task or first X% of documents per task. Useful for debugging, especially on costly API models.
-
diff --git a/lmms-eval-0.2.0.post1/docs/current_tasks.md b/lmms-eval-0.2.0.post1/docs/current_tasks.md
deleted file mode 100644
index 1622e96029dfa8f0b4e94a49060d72c0d7b3d8ce..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/docs/current_tasks.md
+++ /dev/null
@@ -1,122 +0,0 @@
-# Current Tasks
-
-> () indicates the task name in the lmms_eval. The task name is also used to specify the dataset in the configuration file.
-> The following is manually updated documentation. You could use `lmms_eval task --list` to list all supported tasks and their task names.
-
-- AI2D (ai2d)
-- ChartQA (chartqa)
-- CMMMU (cmmmu)
- - CMMMU Validation (cmmmu_val)
- - CMMMU Test (cmmmu_test)
-- COCO Caption (coco_cap)
- - COCO 2014 Caption (coco2014_cap)
- - COCO 2014 Caption Validation (coco2014_cap_val)
- - COCO 2014 Caption Test (coco2014_cap_test)
- - COCO 2017 Caption (coco2017_cap)
- - COCO 2017 Caption MiniVal (coco2017_cap_val)
- - COCO 2017 Caption MiniTest (coco2017_cap_test)
-- [ConBench](https://github.com/foundation-multimodal-models/ConBench) (conbench)
-- DOCVQA (docvqa)
- - DOCVQA Validation (docvqa_val)
- - DOCVQA Test (docvqa_test)
-- Ferret (ferret)
-- Flickr30K (flickr30k)
- - Ferret Test (ferret_test)
-- GQA (gqa)
-- HallusionBenchmark (hallusion_bench_image)
-- Infographic VQA (info_vqa)
- - Infographic VQA Validation (info_vqa_val)
- - Infographic VQA Test (info_vqa_test)
-- LLaVA-Bench (llava_in_the_wild)
-- LLaVA-Bench-COCO (llava_bench_coco)
-- MathVerse (mathverse)
- - MathVerse Text Dominant (mathverse_testmini_text_dominant)
- - MathVerse Text Only (mathverse_testmini_text_only)
- - MathVerse Text Lite (mathverse_testmini_text_lite)
- - MathVerse Vision Dominant (mathverse_testmini_vision_dominant)
- - MathVerse Vision Intensive (mathverse_testmini_vision_intensive)
- - MathVerse Vision Only (mathverse_testmini_vision_only)
-- MathVista (mathvista)
- - MathVista Validation (mathvista_testmini)
- - MathVista Test (mathvista_test)
-- MMBench (mmbench)
- - MMBench English (mmbench_en)
- - MMBench English Dev (mmbench_en_dev)
- - MMBench English Test (mmbench_en_test)
- - MMBench Chinese (mmbench_cn)
- - MMBench Chinese Dev (mmbench_cn_dev)
- - MMBench Chinese Test (mmbench_cn_test)
-- MME (mme)
-- MMMU (mmmu)
- - MMMU Validation (mmmu_val)
- - MMMU Test (mmmu_test)
-- MMUPD (mmupd)
- - MMUPD Base (mmupd_base)
- - MMAAD Base (mmaad_base)
- - MMIASD Base (mmiasd_base)
- - MMIVQD Base (mmivqd_base)
- - MMUPD Option (mmupd_option)
- - MMAAD Option (mmaad_option)
- - MMIASD Option (mmiasd_option)
- - MMIVQD Option (mmivqd_option)
- - MMUPD Instruction (mmupd_instruction)
- - MMAAD Instruction (mmaad_instruction)
- - MMIASD Instruction (mmiasd_instruction)
- - MMIVQD Instruction (mmivqd_instruction)
-- MMVet (mmvet)
-- Multi-DocVQA (multidocvqa)
- - Multi-DocVQA Validation (multidocvqa_val)
- - Multi-DocVQA Test (multidocvqa_test)
-- NoCaps (nocaps)
- - NoCaps Validation (nocaps_val)
- - NoCaps Test (nocaps_test)
-- OKVQA (ok_vqa)
- - OKVQA Validation 2014 (ok_vqa_val2014)
-- POPE (pope)
-- RefCOCO (refcoco)
- - refcoco_seg_test
- - refcoco_seg_val
- - refcoco_seg_testA
- - refcoco_seg_testB
- - refcoco_bbox_test
- - refcoco_bbox_val
- - refcoco_bbox_testA
- - refcoco_bbox_testB
-- RefCOCO+ (refcoco+)
- - refcoco+_seg
- - refcoco+_seg_val
- - refcoco+_seg_testA
- - refcoco+_seg_testB
- - refcoco+_bbox
- - refcoco+_bbox_val
- - refcoco+_bbox_testA
- - refcoco+_bbox_testB
-- RefCOCOg (refcocog)
- - refcocog_seg_test
- - refcocog_seg_val
- - refcocog_bbox_test
- - refcocog_bbox_val
-- ScienceQA (scienceqa_full)
- - ScienceQA Full (scienceqa)
- - ScienceQA IMG (scienceqa_img)
-- ScreenSpot (screenspot)
- - ScreenSpot REC / Grounding (screenspot_rec)
- - ScreenSpot REG / Instruction Generation (screenspot_reg)
-- SeedBench (seedbench)
-- SeedBench 2 (seedbench_2)
-- ST-VQA (stvqa)
-- TextCaps (textcaps)
- - TextCaps Validation (textcaps_val)
- - TextCaps Test (textcaps_test)
-- TextVQA (textvqa)
- - TextVQA Validation (textvqa_val)
- - TextVQA Test (textvqa_test)
-- VizWizVQA (vizwiz_vqa)
- - VizWizVQA Validation (vizwiz_vqa_val)
- - VizWizVQA Test (vizwiz_vqa_test)
-- VQAv2 (vqav2)
- - VQAv2 Validation (vqav2_val)
- - VQAv2 Test (vqav2_test)
-- WebSRC (websrc)
- - WebSRC Validation (websrc_val)
- - WebSRC Test (websrc_test)
\ No newline at end of file
diff --git a/lmms-eval-0.2.0.post1/docs/model_guide.md b/lmms-eval-0.2.0.post1/docs/model_guide.md
deleted file mode 100644
index 0a4e4feedf731b7d95ceac18778cf903b2f3dcf1..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/docs/model_guide.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# New Model Guide
-In order to properly evaluate a given LM, we require implementation of a wrapper class subclassing the `lmms_eval.api.model.lmms` class, that defines how the lmms_eval should interface with your model. This guide walks through how to write this `lmms` subclass via adding it to the library!
-
-## Setup
-
-To get started contributing, go ahead and fork the main repo, clone it, create a branch with the name of your task, and install the project requirements in your environment:
-
-```sh
-# After forking...
-git clone https://github.com//lmms-eval.git
-cd lmms-eval
-git checkout -b
-pip install -e .
-```
-
-Now, we'll create a new file where we'll be adding our model:
-
-```sh
-touch lmms_eval/models/.py
-```
-
-**As a rule of thumb, we recommend you to use `lmms_eval/models/qwen_vl.py` and `lmms_eval/models/instructblip.py` as reference implementations for your model. You can copy and paste the contents of one of these files into your new file to get started.**
-
-## Interface
-
-All models must subclass the `lmms_eval.api.model.lmms` class.
-
-The lmms class enforces a common interface via which we can extract responses from a model:
-
-```python
-class MyCustomLM(lmms):
- #...
- def loglikelihood(self, requests: list[Instance]) -> list[tuple[float, bool]]:
- #...
-
- def generate_until(self, requests: list[Instance]) -> list[str]:
- #...
- #...
-```
-Where `Instance` is a dataclass defined in [`lmms_eval.api.instance`](https://github.com/EvolvingLMMs-Lab/lmms-eval/tree/main/lmms_eval/api/instance.py) with property `args` of request-dependent type signature described below.
-
-We support three types of requests, consisting of different interactions / measurements with an autoregressive LM.
-
-All three request types take as input `requests` of type `list[Instance]` that have a matching `Instance.request_type` to the method name. Overall, you can check the [construct_requests](https://github.com/EvolvingLMMs-Lab/lmms-eval/blob/main/lmms_eval/api/task.py#L918) to see how the arguments are being constructed for different types of output type requests.
-
-- `generate_until`
- - Each request contains `Instance.args : Tuple[str, dict]` containing 1. an input string to the LM and 2. a dictionary of keyword arguments used to control generation parameters.
- - In each `Instance.args` there will be 6 elements which are `contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split`. `contexts` refers to the formatted question and is the text input for the LMM. Sometimes it might contains image token and need to address differently for different models. `all_gen_kwargs` refers to the dict that contains all the generation configuration for the model. We use `doc_id`, `task`, and `split` to access the dataset and then you can use `doc_to_visual` which is a function reference to process the image. When you implement your own model, you should use these to write your own generate_util function.
- - Using this input and these generation parameters, text will be sampled from the language model (typically until a maximum output length or specific stopping string sequences--for example, `{"until": ["\n\n", "."], "max_gen_toks": 128}`).
- - The generated input+output text from the model will then be returned.
-
-- `loglikelihood`
- - Each request contains `Instance.args : Tuple[str, str]` containing 1. an input string to the LM and 2. a target string on which the loglikelihood of the LM producing this target, conditioned on the input, will be returned.
- - In each `Instance.args` there will be 6 elements which are ` contexts, doc_to_target, doc_to_visual, doc_id, task, split`. `contexts` refers to the formatted question and is the text input for the LMM. Sometimes it might contains image token and need to address differently for different models. `doc_to_target` is a function reference that get the get the answer from the doc. This will be the continuation of the answer and only tokens belong to this part should be calculated for the loglikelihood.
- - Each request will have, as result, `(ll, is_greedy): Tuple[float, int]` returned, where `ll` is a floating point number representing the log probability of generating the target string conditioned on the input, and `is_greedy` being either the value `0` or `1`, with it being `1` if and only if the target string *would be generated by greedy sampling from the LM* (that is, if the target string is the *most likely* N-token string to be output by the LM given the input. )
-
-
-
-
-## Registration
-
-Congrats on implementing your model! Now it's time to test it out.
-
-To make your model usable via the command line interface to `lmms_eval`, you'll need to tell `lmms_eval` what your model's name is.
-
-This is done via a *decorator*, `lmms_eval.api.registry.register_model`. Using `register_model()`, one can both tell the package what the model's name(s) to be used are when invoking it with `python -m lm_eval --model ` and alert `lmms_eval` to the model's existence.
-
-```python
-from lmms_eval.api.registry import register_model
-
-@register_model("", "")
-class MyCustomLM(LM):
-```
-
-The final step is to import your model in `lmms_eval/models/__init__.py`:
-```python
-from .my_model_filename import MyCustomLM
-```
diff --git a/lmms-eval-0.2.0.post1/docs/task_guide.md b/lmms-eval-0.2.0.post1/docs/task_guide.md
deleted file mode 100644
index 1376bc22e127089539486ebc2cdf784ccf18ad0d..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/docs/task_guide.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# Task Configuration
-
-The `lmms_eval` is meant to be an extensible and flexible framework within which many different evaluation tasks can be defined. All tasks in the new version of the harness are built around a YAML configuration file format.
-
-These YAML configuration files, along with the current codebase commit hash, are intended to be shareable such that providing the YAML config enables another researcher to precisely replicate the evaluation setup used by another, in the case that the prompt or setup differs from standard `lmms_eval` task implementations.
-
-While adding a standard evaluation task on a new dataset can be occasionally as simple as swapping out a Hugging Face dataset path in an existing file, more specialized evaluation setups also exist. Here we'll provide a crash course on the more advanced logic implementable in YAML form available to users.
-
-## Good Reference Tasks
-
-Contributing a new task can be daunting! Luckily, much of the work has often been done for you in a different, similarly evaluated task. Good examples of task implementations to study include:
-
-Generation-based tasks:
-
-- MME (`lmms_eval/tasks/mme/mme.yaml`)
-
-```yaml
-dataset_path: lmms-lab/MME
-dataset_kwargs:
- token: True
-task: "mme"
-test_split: test
-output_type: generate_until
-doc_to_visual: !function utils.mme_doc_to_visual
-doc_to_text: !function utils.mme_doc_to_text
-doc_to_target: "answer"
-generation_kwargs:
- max_new_tokens: 16
- temperature: 0
- top_p: 1.0
- num_beams: 1
- do_sample: false
-# The return value of process_results will be used by metrics
-process_results: !function utils.mme_process_results
-# Note that the metric name can be either a registed metric function (such as the case for GQA) or a key name returned by process_results
-metric_list:
- - metric: mme_percetion_score
- aggregation: !function utils.mme_aggregate_results
- higher_is_better: true
- - metric: mme_cognition_score
- aggregation: !function utils.mme_aggregate_results
- higher_is_better: true
-model_specific_prompt_kwargs:
- default:
- pre_prompt: ""
- post_prompt: "\nAnswer the question using a single word or phrase."
- qwen_vl:
- pre_prompt: ""
- post_prompt: " Answer:"
-metadata:
- - version: 0.0
-```
-
-You can pay special attention to the `process_results` and `metric_list` fields, which are used to define how the model output is post-processed and scored.
-Also, the `model_specific_prompt_kwargs` field is used to define model-specific prompt configurations. The default is set to follow Llava.
-
-PPL-based tasks:
-- Seedbench (`lmms_eval/tasks/seedbench/seedbench_ppl.yaml`)
-
-```yaml
-dataset_path: lmms-lab/SEED-Bench
-dataset_kwargs:
- token: True
-task: "seedbench_ppl"
-test_split: test
-output_type: multiple_choice
-doc_to_visual: !function utils.seed_doc_to_visual
-doc_to_text: !function utils.seed_doc_to_text_mc
-doc_to_choice : !function utils.seed_doc_to_choice
-doc_to_target: !function utils.seed_doc_to_mc_target
-# Note that the metric name can be either a registed metric function (such as the case for GQA) or a key name returned by process_results
-metric_list:
- - metric: acc
-metadata:
- - version: 0.0
-```
-
-## Configurations
-
-Tasks are configured via the `TaskConfig` object. Below, we describe all fields usable within the object, and their role in defining a task.
-
-### Parameters
-
-Task naming + registration:
-- **task** (`str`, defaults to None) — name of the task.
-- **group** (`str`, *optional*) — name of the task group(s) a task belongs to. Enables one to run all tasks with a specified tag or group name at once.
-
-Dataset configuration options:
-- **dataset_path** (`str`) — The name of the dataset as listed by HF in the datasets Hub.
-- **dataset_name** (`str`, *optional*, defaults to None) — The name of what HF calls a “config” or sub-task of the benchmark. If your task does not contain any data instances, just leave this to default to None. (If you're familiar with the HF `datasets.load_dataset` function, these are just the first 2 arguments to it.)
-- **dataset_kwargs** (`dict`, *optional*) — Auxiliary arguments that `datasets.load_dataset` accepts. This can be used to specify arguments such as `data_files` or `data_dir` if you want to use local datafiles such as json or csv.
-- **training_split** (`str`, *optional*) — Split in the dataset to use as the training split.
-- **validation_split** (`str`, *optional*) — Split in the dataset to use as the validation split.
-- **test_split** (`str`, *optional*) — Split in the dataset to use as the test split.
-- **fewshot_split** (`str`, *optional*) — Split in the dataset to draw few-shot exemplars from. assert that this not None if num_fewshot > 0. **This function is not well tested so far**
-- **process_docs** (`Callable`, *optional*) — Optionally define a function to apply to each HF dataset split, to preprocess all documents before being fed into prompt template rendering or other evaluation steps. Can be used to rename dataset columns, or to process documents into a format closer to the expected format expected by a prompt template.
-
-Prompting / in-context formatting options:
-- **doc_to_text** (`Union[Callable, str]`, *optional*) — Column name or function to process a sample into the appropriate input for the model
-- **doc_to_visial** (`Union[Callable, str]`, *optional*) — Function to process a sample into the appropriate input images for the model.
-- **doc_to_target** (`Union[Callable, str]`, *optional*) — Column name or or function to process a sample into the appropriate target output for the model. For multiple choice tasks, this should return an index into
-- **doc_to_choice** (`Union[Callable, str]`, *optional*) — Column name or or function to process a sample into a list of possible string choices for `multiple_choice` tasks. Left undefined for `generate_until` tasks.
-
-Runtime configuration options:
-- **num_fewshot** (`int`, *optional*, defaults to 0) — Number of few-shot examples before the input. **This function is not well tested so far**
-- **batch_size** (`int`, *optional*, defaults to 1) — Batch size.
-
-**So far some models (such as qwen) may not support batch size > 1. Some models (such as llava) will generate different scores for different batch sizes. We recommend setting batch size to 1 for final benchmarking runs.**
-
-Scoring details:
-- **metric_list** (`str`, *optional*, defaults to None) — A list of metrics to use for evaluation.
-- **output_type** (`str`, *optional*, defaults to "generate_until") — Selects the type of model output for the given task. Options are `generate_until`, `loglikelihood`, and `multiple_choice`.
-- **generation_kwargs** (`dict`, *optional*) — Auxiliary arguments for the `generate` function from HF transformers library. Advanced keyword arguments may not be supported for non-HF LM classes.
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/__main__.py b/lmms-eval-0.2.0.post1/lmms_eval/__main__.py
deleted file mode 100644
index 96be8f06a531fb445abc3a708ed5a8cbc8f4c55b..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/__main__.py
+++ /dev/null
@@ -1,345 +0,0 @@
-import os
-import yaml
-import sys
-import json
-
-import traceback
-import argparse
-import numpy as np
-import datetime
-
-import warnings
-import traceback
-
-warnings.simplefilter("ignore", category=DeprecationWarning)
-
-from accelerate import Accelerator
-from accelerate.utils import InitProcessGroupKwargs
-from pathlib import Path
-from typing import Union
-import hashlib
-
-from lmms_eval import evaluator, utils
-from lmms_eval.tasks import initialize_tasks, include_path, get_task_dict
-from lmms_eval.api.registry import ALL_TASKS
-from lmms_eval.logging_utils import WandbLogger
-from loguru import logger as eval_logger
-
-
-def _handle_non_serializable(o):
- if isinstance(o, np.int64) or isinstance(o, np.int32):
- return int(o)
- elif isinstance(o, set):
- return list(o)
- else:
- return str(o)
-
-
-def parse_eval_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
- parser.add_argument("--config", default="", help="Path to a yaml file specifying all eval arguments, will ignore cli arguments if specified")
- parser.add_argument("--model", default="hf", help="Name of model e.g. `hf`")
- parser.add_argument(
- "--tasks",
- default=None,
- help="To get full list of tasks, use the command lmms-eval --tasks list",
- )
- parser.add_argument(
- "--model_args",
- default="",
- help="String arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`",
- )
- parser.add_argument(
- "--num_fewshot",
- type=int,
- default=None,
- help="Number of examples in few-shot context",
- )
- parser.add_argument("--batch_size", type=str, default=1)
- parser.add_argument(
- "--device",
- type=str,
- default=None,
- help="Device to use (e.g. cuda, cuda:0, cpu)",
- )
- parser.add_argument(
- "--output_path",
- default=None,
- type=str,
- metavar="= [dir/file.jsonl] [DIR]",
- help="The path to the output file where the result metrics will be saved. If the path is a directory and log_samples is true, the results will be saved in the directory. Else the parent directory will be used.",
- )
- parser.add_argument(
- "--limit",
- type=float,
- default=None,
- help="Limit the number of examples per task. " "If <1, limit is a percentage of the total number of examples.",
- )
- parser.add_argument(
- "--check_integrity",
- action="store_true",
- help="Whether to run the relevant part of the test suite for the tasks",
- )
- parser.add_argument(
- "--show_task_to_terminal",
- action="store_true",
- default=False,
- help="Prints the prompt for the first few documents",
- )
- parser.add_argument(
- "--log_samples",
- action="store_true",
- default=False,
- help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis",
- )
- parser.add_argument(
- "--wandb_log_samples",
- action="store_true",
- default=False,
- help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis to Weights and Biases",
- )
- parser.add_argument(
- "--log_samples_suffix",
- type=str,
- default="model_outputs",
- help="Specify a suffix for the log_samples file name.",
- )
- parser.add_argument(
- "--predict_only",
- "-x",
- action="store_true",
- default=False,
- help="Use with --log_samples. Only model outputs will be saved and metrics will not be evaluated.",
- )
- parser.add_argument(
- "--show_config",
- action="store_true",
- default=False,
- help="If True, shows the the full config of all tasks at the end of the evaluation.",
- )
- parser.add_argument(
- "--include_path",
- type=str,
- default=None,
- help="Additional path to include if there are external tasks to include.",
- )
- parser.add_argument(
- "--gen_kwargs",
- default="",
- help=("String arguments for model generation on greedy_until tasks," " e.g. `temperature=0,top_k=0,top_p=0`"),
- )
- parser.add_argument(
- "--verbosity",
- type=str,
- default="INFO",
- help="Log error when tasks are not registered.",
- )
- parser.add_argument(
- "--wandb_args",
- default="",
- help="Comma separated string arguments passed to wandb.init, e.g. `project=lmms-eval,job_type=eval",
- )
- parser.add_argument(
- "--timezone",
- default="Asia/Singapore",
- help="Timezone for datetime string, e.g. Asia/Singapore, America/New_York, America/Los_Angeles",
- )
- args = parser.parse_args()
- return args
-
-
-def cli_evaluate(args: Union[argparse.Namespace, None] = None) -> None:
- if not args:
- args = parse_eval_args()
-
- # Check if no arguments were passed after parsing
- if len(sys.argv) == 1:
- print("┌───────────────────────────────────────────────────────────────────────────────┐")
- print("│ Please provide arguments to evaluate the model. e.g. │")
- print("│ `lmms-eval --model llava --model_path liuhaotian/llava-v1.6-7b --tasks okvqa` │")
- print("│ Use `lmms-eval --help` for more information. │")
- print("└───────────────────────────────────────────────────────────────────────────────┘")
- sys.exit(1)
-
- # reset logger
- eval_logger.remove()
- eval_logger.add(sys.stdout, colorize=True, level=args.verbosity)
- eval_logger.add(sys.stderr, level=args.verbosity)
- eval_logger.info(f"Verbosity set to {args.verbosity}")
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
-
- args_list = []
- results_list = []
- if args.config:
- if not os.path.exists(args.config):
- raise ValueError(f"Config file does not exist: {args.config}")
-
- with open(args.config, "r") as file:
- config_args = yaml.safe_load(file)
- config_args = [config_args] if type(config_args) != list else config_args
- # multiple configs, create args list first
- for config in config_args:
- args_copy = argparse.Namespace(**vars(args))
- for key, value in config.items():
- setattr(args_copy, key, value)
- args_list.append(args_copy)
- else:
- args_list.append(args)
-
- # initialize Accelerator
- kwargs_handler = InitProcessGroupKwargs(timeout=datetime.timedelta(seconds=60000))
- accelerator = Accelerator(kwargs_handlers=[kwargs_handler])
- if accelerator.is_main_process:
- is_main_process = True
- else:
- is_main_process = False
-
- for args in args_list:
- try:
- if is_main_process and args.wandb_args: # thoughtfully we should only init wandb once, instead of multiple ranks to avoid network traffics and unwanted behaviors.
- wandb_logger = WandbLogger(args)
-
- results, samples = cli_evaluate_single(args)
- results_list.append(results)
-
- accelerator.wait_for_everyone()
- if is_main_process and args.wandb_args:
- wandb_logger.post_init(results)
- wandb_logger.log_eval_result()
- if args.wandb_log_samples and samples is not None:
- wandb_logger.log_eval_samples(samples)
-
- wandb_logger.finish()
-
- except Exception as e:
- traceback.print_exc()
- eval_logger.error(f"Error during evaluation: {e}")
- traceback.print_exc()
- results_list.append(None)
-
- for args, results in zip(args_list, results_list):
- # cli_evaluate will return none if the process is not the main process (rank 0)
- if results is not None:
- print_results(args, results)
-
-
-def cli_evaluate_single(args: Union[argparse.Namespace, None] = None) -> None:
- initialize_tasks(args.verbosity)
-
- if args.predict_only:
- args.log_samples = True
- if (args.log_samples or args.predict_only) and not args.output_path:
- raise ValueError("Specify --output_path if providing --log_samples or --predict_only")
- if args.limit:
- eval_logger.warning(" --limit SHOULD ONLY BE USED FOR TESTING." "REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")
- if args.include_path is not None:
- eval_logger.info(f"Including path: {args.include_path}")
- include_path(args.include_path)
-
- if args.tasks is None:
- task_names = ALL_TASKS
- elif args.tasks == "list":
- eval_logger.info("Available Tasks:\n - {}".format(f"\n - ".join(sorted(ALL_TASKS))))
- sys.exit()
- elif args.tasks == "list_with_num":
- log_message = (
- "\n" + "=" * 70 + "\n" + "\n\tYou are trying to check all the numbers in each task." + "\n\tThis action will download the complete dataset." + "\n\tIf the results are not clear initially, call this again." + "\n\n" + "=" * 70
- )
- eval_logger.info(log_message)
- for task_name in sorted(ALL_TASKS):
- try:
- task_dict = get_task_dict([task_name], model_name="llava")
- task_obj = task_dict[task_name]
- if type(task_obj) == tuple:
- group, task_obj = task_obj
- if task_obj is None:
- continue
- eval_logger.info(f"\nTask : {task_obj.config.task}\n - #num : {len(task_obj.test_docs()) if task_obj.has_test_docs() else len(task_obj.validation_docs())}")
- except Exception as e:
- eval_logger.debug(f"\nTask : {task_name} fail to load \n Exception : \n {e}")
- sys.exit()
- else:
- tasks_list = args.tasks.split(",")
- eval_logger.info(f"Evaluating on {len(tasks_list)} tasks.")
- task_names = utils.pattern_match(tasks_list, ALL_TASKS)
- task_missing = [task for task in tasks_list if task not in task_names and "*" not in task] # we don't want errors if a wildcard ("*") task name was used
-
- if task_missing:
- missing = ", ".join(task_missing)
- eval_logger.error(
- f"Tasks were not found: {missing}. Try `lmms-eval --tasks list` for list of available tasks",
- )
- # eval_logger.warn(f"Tasks {missing} were not found. Try `lmms-eval --tasks list` for list of available tasks.")
-
- eval_logger.info(f"Selected Tasks: {task_names}")
-
- # set datetime before evaluation
- datetime_str = utils.get_datetime_str(timezone=args.timezone)
- if args.output_path:
- if args.log_samples_suffix and len(args.log_samples_suffix) > 15:
- eval_logger.warning("The suffix for log_samples is too long. It is recommended to keep it under 15 characters.")
- args.log_samples_suffix = args.log_samples_suffix[:5] + "..." + args.log_samples_suffix[-5:]
-
- hash_input = f"{args.model_args}".encode("utf-8")
- hash_output = hashlib.sha256(hash_input).hexdigest()[:6]
- path = Path(args.output_path)
- path = path.expanduser().resolve().joinpath(f"{datetime_str}_{args.log_samples_suffix}_{args.model}_model_args_{hash_output}")
- args.output_path = path
-
- elif args.log_samples and not args.output_path:
- assert args.output_path, "Specify --output_path"
-
- results = evaluator.simple_evaluate(
- model=args.model,
- model_args=args.model_args,
- tasks=task_names,
- num_fewshot=args.num_fewshot,
- batch_size=args.batch_size,
- device=args.device,
- limit=args.limit,
- check_integrity=args.check_integrity,
- show_task_to_terminal=args.show_task_to_terminal,
- log_samples=args.log_samples,
- gen_kwargs=args.gen_kwargs,
- cli_args=args,
- predict_only=args.predict_only,
- )
-
- if results is not None:
- if args.log_samples:
- samples = results.pop("samples")
- else:
- samples = None
- dumped = json.dumps(results, indent=4, default=_handle_non_serializable)
- if args.show_config:
- print(dumped)
-
- if args.output_path:
- args.output_path.mkdir(parents=True, exist_ok=True)
- result_file_path = path.joinpath("results.json")
- if result_file_path.exists():
- eval_logger.warning(f"Output file {result_file_path} already exists and will be overwritten.")
-
- result_file_path.open("w").write(dumped)
- if args.log_samples:
- for task_name, config in results["configs"].items():
- filename = args.output_path.joinpath(f"{task_name}.json")
- # Structure the data with 'args' and 'logs' keys
- data_to_dump = {"args": vars(args), "model_configs": config, "logs": sorted(samples[task_name], key=lambda x: x["doc_id"]), "time": datetime_str}
- samples_dumped = json.dumps(data_to_dump, indent=4, default=_handle_non_serializable, ensure_ascii=False)
- filename.open("w", encoding="utf-8").write(samples_dumped)
- eval_logger.info(f"Saved samples to {filename}")
-
- return results, samples
- return None, None
-
-
-def print_results(args, results):
- print(f"{args.model} ({args.model_args}),\ngen_kwargs: ({args.gen_kwargs}),\nlimit: {args.limit},\nnum_fewshot: {args.num_fewshot},\nbatch_size: {args.batch_size}")
- print(evaluator.make_table(results))
- if "groups" in results:
- print(evaluator.make_table(results, "groups"))
-
-
-if __name__ == "__main__":
- cli_evaluate()
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/api/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/filter.py b/lmms-eval-0.2.0.post1/lmms_eval/api/filter.py
deleted file mode 100644
index 3fc6435dd991ff7fa89198a2e68a9ba994005d31..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/filter.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from dataclasses import dataclass
-from typing import List
-
-from lmms_eval.api.instance import Instance
-from datasets import Dataset
-
-
-class Filter:
- """
- Filter classes operate on a per-task level.
- They take all model outputs (`instance.resps` for all `task.instances`)
- across all instances of a task, and perform operations.
- In a single run, one can configure any number of separate filters or lists of filters.
-
- """
-
- def __init__(self, *args, **kwargs) -> None:
- """
- Can define custom behavior here, if an individual instantiation of a Filter class should have state.
- """
-
- def apply(self, resps, docs):
- """
- Defines the operation to perform on a list of the `inst.resps` properties of `Instance` objects.
- Should return the list of (filtered) response lists *in the same order as they were input*, e.g.
- if pass in [, ] should return
- [, ]
- """
- return resps
-
-
-@dataclass
-class FilterEnsemble:
- """
- FilterEnsemble creates a pipeline applying multiple filters.
- Its intended usage is to stack multiple post-processing steps in order.
- `task.apply_filters` should use a list of FilterEnsemble classes that it stores, to apply each
- pipeline separately.
- """
-
- name: str
- filters: List[Filter]
-
- def apply(self, instances: List[Instance], docs: List[Dataset]) -> None:
- resps = [inst.resps for inst in instances] # operate just on the model responses
- for f in self.filters:
- # apply filters in sequence
- resps = f.apply(resps, docs)
-
- # add the end results after filtering to filtered_requests of their respective source instances.
- # has key `self.name`: each FilterEnsemble applied in a given run should use a different name.
- for inst, resp in zip(instances, resps):
- inst.filtered_resps[self.name] = resp
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/instance.py b/lmms-eval-0.2.0.post1/lmms_eval/api/instance.py
deleted file mode 100644
index 41875358d16f1a9322cd67aba9101f80eb72d4dd..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/instance.py
+++ /dev/null
@@ -1,29 +0,0 @@
-from dataclasses import dataclass, field
-from typing import Literal, Tuple
-
-
-@dataclass
-class Instance:
- request_type: Literal["loglikelihood", "generate_until"]
- arguments: tuple
- idx: int
- metadata: Tuple[str, int, int] = field(default_factory=lambda: (None, None, None)) # TODO: better typehints here
- resps: list = field(default_factory=list)
- filtered_resps: dict = field(default_factory=dict)
-
- # initialized after init
- task_name: str = None
- doc_id: str = None
- repeats: str = None
- doc: dict = None
-
- def __post_init__(self) -> None:
- # unpack metadata field
- self.task_name, self.doc_id, self.repeats = self.metadata
-
- @property
- def args(self):
- """
- Returns (string,) where `string` is the string to calculate loglikelihood over
- """
- return self.arguments if isinstance(self.arguments, tuple) else (self.arguments,)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/metrics.py b/lmms-eval-0.2.0.post1/lmms_eval/api/metrics.py
deleted file mode 100644
index 157ed2df58c41a1b9da936b44c00a9d16dbb6dea..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/metrics.py
+++ /dev/null
@@ -1,443 +0,0 @@
-import math
-from collections.abc import Iterable
-
-import numpy as np
-import sacrebleu
-import sklearn.metrics
-import random
-import evaluate
-import torch
-
-from lmms_eval.api.registry import register_metric, register_aggregation
-from loguru import logger as eval_logger
-
-
-# Register Aggregations First
-@register_aggregation("bypass")
-def bypass_agg(arr):
- return 999
-
-
-@register_aggregation("mean")
-def mean(arr):
- return sum(arr) / len(arr)
-
-
-@register_aggregation("median")
-def median(arr):
- return arr[len(arr) // 2]
-
-
-# Certain metrics must be calculated across all documents in a benchmark.
-# We use them as aggregation metrics, paired with no-op passthrough metric fns.
-@register_aggregation("perplexity")
-def perplexity(items):
- # return math.exp(-mean(items))
- items = torch.exp(torch.tensor(items)).tolist()
- return sum(items) / len(items)
-
-
-@register_aggregation("weighted_perplexity")
-def weighted_perplexity(items):
- return math.exp(-weighted_mean(items))
-
-
-@register_aggregation("bits_per_byte")
-def bits_per_byte(items):
- return -weighted_mean(items) / math.log(2)
-
-
-@register_aggregation("f1")
-def f1_score(items):
- unzipped_list = list(zip(*items))
- golds = unzipped_list[0]
- preds = unzipped_list[1]
- fscore = sklearn.metrics.f1_score(golds, preds)
-
- return np.max(fscore)
-
-
-@register_aggregation("matthews_corrcoef")
-def matthews_corrcoef(items):
- unzipped_list = list(zip(*items))
- golds = unzipped_list[0]
- preds = unzipped_list[1]
- # print(preds)
- return sklearn.metrics.matthews_corrcoef(golds, preds)
-
-
-@register_aggregation("bleu")
-def bleu(items):
- """The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric
- for evaluating a generated sentence to a reference sentence. It counts matching
- n-grams in the candidate translation to n-grams in the reference text, where
- 1-gram or unigram would be each token and a bigram comparison would be each
- word pair. The comparison is made regardless of word order
- Source: https://machinelearningmastery.com/calculate-bleu-score-for-text-python/
- Paper: https://www.aclweb.org/anthology/P02-1040/
-
- Higher is better
- """
- refs = list(zip(*items))[0]
- preds = list(zip(*items))[1]
- refs, preds = _sacreformat(refs, preds)
- return sacrebleu.corpus_bleu(preds, refs).score
-
-
-@register_aggregation("chrf")
-def chrf(items):
- """chrF++ is a tool for automatic evaluation of machine translation output
- based on character n-gram precision and recall enhanced with word n-grams.
- Source: https://github.com/m-popovic/chrF
- Paper: https://www.aclweb.org/anthology/W15-3049.pdf
-
- Higher is better # TODO I think
- """
- refs = list(zip(*items))[0]
- preds = list(zip(*items))[1]
- refs, preds = _sacreformat(refs, preds)
- return sacrebleu.corpus_chrf(preds, refs).score
-
-
-@register_aggregation("ter")
-def ter(items):
- """Translation Error Rate is an error metric for machine translation that
- measures the number of edits required to change a system output into one
- of the references
- Source: http://www.cs.umd.edu/~snover/tercom/
- Paper: http://mt-archive.info/AMTA-2006-Snover.pdf
-
- Lower is better
- """
- refs = list(zip(*items))[0]
- preds = list(zip(*items))[1]
- refs, preds = _sacreformat(refs, preds)
- return sacrebleu.corpus_ter(preds, refs).score
-
-
-@register_metric(
- metric="acc",
- higher_is_better=True,
- output_type=["loglikelihood", "multiple_choice"],
- aggregation="mean",
-)
-def acc_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="acc_norm",
- higher_is_better=True,
- output_type=["loglikelihood", "multiple_choice"],
- aggregation="mean",
-)
-def acc_norm_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="acc_mutual_info",
- higher_is_better=True,
- output_type="multiple_choice",
- aggregation="mean",
-)
-def acc_mutual_info_fn(items): # This is a passthrough function
- return items
-
-
-exact_match = evaluate.load("exact_match")
-
-
-@register_metric(
- metric="exact_match",
- higher_is_better=True,
- output_type="generate_until",
- aggregation="mean",
-)
-def exact_match_fn(**kwargs):
- return exact_match.compute(**kwargs)
-
-
-@register_metric(
- metric="perplexity",
- higher_is_better=False,
- output_type="loglikelihood",
- aggregation="perplexity",
-)
-def perplexity_fn(items): # This is a passthrough function
- return items
-
-
-def levenshtein_distance(s1, s2):
- if len(s1) > len(s2):
- s1, s2 = s2, s1
-
- distances = range(len(s1) + 1)
- for i2, c2 in enumerate(s2):
- distances_ = [i2 + 1]
- for i1, c1 in enumerate(s1):
- if c1 == c2:
- distances_.append(distances[i1])
- else:
- distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
- distances = distances_
- return distances[-1]
-
-
-@register_metric(
- metric="anls",
- higher_is_better=True,
- output_type="generate_until",
- aggregation="mean",
-)
-def anls(
- references,
- predictions,
- thresh_hold=0.5,
-): # This is a passthrough function
- """https://github.com/QwenLM/Qwen-VL/blob/master/eval_mm/infographicsvqa_eval.py"""
- values = []
- for answer in references:
- # preprocess both the answers - gt and prediction
- gt_answer = " ".join(answer.strip().lower().split())
- det_answer = " ".join(predictions[0].strip().lower().split())
-
- # dist = levenshtein_distance(answer.lower(), detObject['answer'].lower())
- dist = levenshtein_distance(gt_answer, det_answer)
- length = max(len(answer.upper()), len(predictions[0].upper()))
- values.append(0.0 if length == 0 else float(dist) / float(length))
-
- question_result = 1 - min(values)
-
- if question_result < thresh_hold:
- question_result = 0
- return {"anls": question_result}
-
-
-def pop_stddev(arr):
- mu = mean(arr)
- return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / len(arr))
-
-
-def sample_stddev(arr):
- mu = mean(arr)
- return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / (len(arr) - 1))
-
-
-def mean_stderr(arr):
- return sample_stddev(arr) / math.sqrt(len(arr))
-
-
-@register_metric(
- metric="bypass",
- higher_is_better=True,
- output_type=["loglikelihood", "multiple_choice", "generate_until"],
- aggregation="bypass",
-)
-def bypass(items):
- return items
-
-
-@register_metric(
- metric="mcc",
- higher_is_better=True,
- output_type="multiple_choice",
- aggregation="matthews_corrcoef",
-)
-def mcc_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="f1",
- higher_is_better=True,
- output_type="multiple_choice",
- aggregation="f1",
-)
-def f1_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="bleu",
- higher_is_better=True,
- output_type="generate_until",
- aggregation="bleu",
-)
-def bleu_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="chrf",
- higher_is_better=True,
- output_type="generate_until",
- aggregation="chrf",
-)
-def chrf_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="ter",
- higher_is_better=True,
- output_type="generate_until",
- aggregation="ter",
-)
-def ter_fn(items): # This is a passthrough function
- return items
-
-
-@register_metric(
- metric="acc_all",
- higher_is_better=True,
- output_type="loglikelihood",
- aggregation="mean",
-)
-def acc_all(items):
- # Only count as correct if all answers are labeled correctly for each question
- question_scoring_dict = {}
- preds = list(zip(*items))[0]
- docs = list(zip(*items))[1]
-
- for doc, pred in zip(docs, preds):
- paragraph_id = doc["idx"]["paragraph"]
- question_id = doc["idx"]["question"]
- if (paragraph_id, question_id) not in question_scoring_dict:
- question_scoring_dict[(paragraph_id, question_id)] = []
-
- gold_label = doc["label"] == 1
-
- question_scoring_dict[(paragraph_id, question_id)].append(gold_label == pred)
- acc = np.mean([int(all(x)) for x in question_scoring_dict.values()])
- return acc
-
-
-def acc_all_stderr(items):
- # Only count as correct if all answers are labeled correctly for each question
- question_scoring_dict = {}
- preds = list(zip(*items))[0]
- docs = list(zip(*items))[1]
-
- for doc, pred in zip(docs, preds):
- question_id = doc["idx"]["question"]
- if question_id not in question_scoring_dict:
- question_scoring_dict[question_id] = []
-
- gold_label = doc["label"] == 1
- question_scoring_dict[question_id].append(gold_label == pred)
-
- acc = mean_stderr([int(all(x)) for x in question_scoring_dict.values()])
- return acc
-
-
-def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
- """Compute max metric between prediction and each ground truth."""
- scores_for_ground_truths = []
- for ground_truth in ground_truths:
- score = metric_fn(prediction, ground_truth)
- scores_for_ground_truths.append(score)
- return max(scores_for_ground_truths)
-
-
-def weighted_mean(items):
- a, b = zip(*items)
- return sum(a) / sum(b)
-
-
-def is_non_str_iterable(obj):
- return isinstance(obj, Iterable) and not isinstance(obj, str)
-
-
-def _sacreformat(refs, preds):
- """Format refs and preds for sacrebleu corpus calculation. It is very particular"""
- # Sacrebleu expects (List[str], List[List[str])
- # e.g. sacrebleu.corpus_bleu([pred_t], [[ref1_stream], [ref2_stream], ...])
-
- # Note [ref1_stream] is the first reference for each pred.
- # So lists are size N and (M, N) for N preds and M possible refs for each pred
- # This is a different order of dimensions that I would expect
-
- # We expect refs to be List[str] or List[List[str]], the outer list corresponding to preds
- # Must become List[List[str]] with the inner list corresponding to preds
- if not is_non_str_iterable(refs):
- refs = list(refs)
- if not is_non_str_iterable(refs[0]):
- refs = [[ref] for ref in refs]
- refs = list(zip(*refs))
- # Note the number of refs in each ref list much match the number of preds
-
- # We expect preds to be List[str] or List[List[str]]. Must become List[str]
- if not is_non_str_iterable(preds):
- preds = list(preds)
- if is_non_str_iterable(preds[0]):
- assert len(preds[0]) == 1, f"Pred must be a str, was {preds[0]}"
- preds = [pred[0] for pred in preds]
-
- return refs, preds
-
-
-# stderr stuff
-
-
-class _bootstrap_internal:
- def __init__(self, f, n) -> None:
- self.f = f
- self.n = n
-
- def __call__(self, v):
- i, xs = v
- rnd = random.Random()
- rnd.seed(i)
- res = []
- for _ in range(self.n):
- res.append(self.f(rnd.choices(xs, k=len(xs))))
- return res
-
-
-def bootstrap_stderr(f, xs, iters):
- import multiprocessing as mp
-
- pool = mp.Pool(mp.cpu_count())
- # this gives a biased estimate of the stderr (i.e w/ the mean, it gives something
- # equivalent to stderr calculated without Bessel's correction in the stddev.
- # Unfortunately, I haven't been able to figure out what the right correction is
- # to make the bootstrap unbiased - i considered multiplying by sqrt(n/(n-1)) but
- # that would be ad-hoc and I can't prove that that would actually be an unbiased estimator)
- # Thankfully, shouldn't matter because our samples are pretty big usually anyways
- res = []
- chunk_size = min(1000, iters)
- from tqdm import tqdm
-
- print("bootstrapping for stddev:", f.__name__)
- for bootstrap in tqdm(
- pool.imap(
- _bootstrap_internal(f, chunk_size),
- [(i, xs) for i in range(iters // chunk_size)],
- ),
- total=iters // chunk_size,
- ):
- # sample w replacement
- res.extend(bootstrap)
-
- pool.close()
- return sample_stddev(res)
-
-
-def stderr_for_metric(metric, bootstrap_iters):
- bootstrappable = [
- median,
- matthews_corrcoef,
- f1_score,
- perplexity,
- bleu,
- chrf,
- ter,
- ]
-
- if metric in bootstrappable:
- return lambda x: bootstrap_stderr(metric, x, iters=bootstrap_iters)
-
- stderr = {mean: mean_stderr, acc_all: acc_all_stderr}
-
- return stderr.get(metric, None)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/model.py b/lmms-eval-0.2.0.post1/lmms_eval/api/model.py
deleted file mode 100644
index e6eeaba64c73c9a11b73a388d309d312757f8360..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/model.py
+++ /dev/null
@@ -1,203 +0,0 @@
-import abc
-import os
-
-from typing import Union, List, Tuple, Optional, Type, TypeVar
-from sqlitedict import SqliteDict
-import json
-import hashlib
-from lmms_eval.api.instance import Instance
-from tqdm import tqdm
-from lmms_eval import utils
-
-
-from loguru import logger as eval_logger
-
-T = TypeVar("T", bound="lmms")
-
-
-class lmms(abc.ABC):
- def __init__(self) -> None:
- """Defines the interface that should be implemented by all lmms subclasses.
- lmmss are assumed to take image-text as input and yield strings as output
- (inputs/outputs should be tokenization-agnostic.)
- """
- # set rank and world size to a single process, by default.
- self._rank = 0
- self._world_size = 1
- self.cache_hook = CacheHook(None)
- self.task_dict = {}
-
- @abc.abstractmethod
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- """Compute log-likelihood of generating a continuation from a context.
- Downstream tasks should attempt to use loglikelihood instead of other
- LMM calls whenever possible.
-
- :param requests: list[Instance]
- A list of Instance objects, with property `args` which returns a tuple (context, continuation).
- `context: str`
- Context string. Implementations of LMM must be able to handle an
- empty context string.
- `continuation: str`
- The continuation over which log likelihood will be calculated. If
- there is a word boundary, the space should be in the continuation.
- For example, context="hello" continuation=" world" is correct.
- 'visual_list: list[dict]'
- Visual input to the model. Can be None.
-
- :return: list[tuple[float, bool]]
- A list of pairs (logprob, isgreedy)
- `logprob: float`
- The log probability of `continuation`.
- `isgreedy`:
- Whether `continuation` would be generated by greedy sampling from `context`.
- """
- pass
-
- # TODO: Add an optional max length
- @abc.abstractmethod
- def generate_until(self, requests) -> List[str]:
- """Generate greedily until a stopping sequence
-
- :param requests: list[Instance]
- A list of Instance objects with property `args` which returns a tuple (context, until).
- context: str
- Context string
- generation_kwargs: dict
- Generation Kwargs
- 'visual_list: list[dict]'
- Visual input to the model. Can be None.
- :return: list[str]
- A list of strings continuation
- continuation: str
- The generated continuation.
- """
- pass
-
- @classmethod
- def create_from_arg_string(cls: Type[T], arg_string: str, additional_config: Optional[dict] = None) -> T:
- """
- Creates an instance of the LMM class using the given argument string and additional config.
-
- Parameters:
- - arg_string: A string containing arguments in the format key1=value1,key2=value2.
- - additional_config: Optional dictionary containing additional configuration parameters.
-
- Returns:
- - Instance of the LMM class.
- """
- additional_config = {} if additional_config is None else additional_config
- args = utils.simple_parse_args_string(arg_string)
- args2 = {k: v for k, v in additional_config.items() if v is not None}
- return cls(**args, **args2)
-
- @property
- def rank(self):
- # used in the case of parallelism. Hardcoded to
- # ensure no errors arise using API models which do
- # not support multi-device parallelism nor expect it.
- return self._rank
-
- @property
- def world_size(self):
- # used in the case of parallelism. Hardcoded to
- # ensure no errors arise using API models which do
- # not support multi-device parallelism nor expect it.
- return self._world_size
-
- def set_cache_hook(self, cache_hook) -> None:
- self.cache_hook = cache_hook
-
-
-### SQLite-based caching of LMM responses
-def hash_args(attr, args):
- dat = json.dumps([attr] + list(args))
- return hashlib.sha256(dat.encode("utf-8")).hexdigest()
-
-
-class CacheHook:
- def __init__(self, cachinglm) -> None:
- if cachinglm is None:
- self.dbdict = None
- return
-
- self.dbdict = cachinglm.dbdict
-
- def add_partial(self, attr, req, res) -> None:
- if self.dbdict is None:
- return
- hsh = hash_args(attr, req)
- self.dbdict[hsh] = res
-
-
-class CachingLMM:
- def __init__(self, lm, cache_db) -> None:
- """LMM wrapper that returns cached results if they exist, and uses the underlying LMM if not.
-
- :param lm: LMM
- Underlying LMM
- :param cache_db: str
- Path to cache db
- """
- self.lm = lm
- self.cache_db = cache_db
- if os.path.dirname(cache_db):
- os.makedirs(os.path.dirname(cache_db), exist_ok=True)
- self.dbdict = SqliteDict(cache_db, autocommit=True)
-
- # add hook to lm
- lm.set_cache_hook(self.get_cache_hook())
-
- def __getattr__(self, attr):
- lm_attr = getattr(self.lm, attr)
- if not callable(lm_attr):
- return lm_attr
-
- def fn(requests):
- res = []
- remaining_reqs = []
- warned = False
- # figure out which ones are cached and which ones are new
- eval_logger.info(f"Loading '{attr}' responses from cache '{self.cache_db}' where possible...")
- for req in tqdm(requests):
- hsh = hash_args(attr, req.args)
- if attr == "generate_until" and req.args[1].get("do_sample", False):
- # when we are doing non-greedy generation, don't use the cache
- # (else every "randomly sampled" generation would be identical for repeats > 1).
- if not warned:
- eval_logger.warning(f"Arguments to lm.generate_until() '{req.args[1]}' include non-deterministic sampling. Caching will not be performed for such requests.")
- warned = True
- res.append(None)
- remaining_reqs.append(req)
- elif hsh in self.dbdict:
- ob = self.dbdict[hsh]
-
- assert ob is not None
-
- res.append(ob)
- else:
- res.append(None)
- remaining_reqs.append(req)
-
- # actually run the LMM on the requests that do not have cached results
- rem_res = getattr(self.lm, attr)(remaining_reqs)
-
- # stick the new ones back into the list and also cache any of the new ones
- resptr = 0
- for req, r in zip(remaining_reqs, rem_res):
- while res[resptr] is not None:
- resptr += 1
-
- res[resptr] = r
-
- # caching
- hsh = hash_args(attr, req.args)
- self.dbdict[hsh] = r
- self.dbdict.commit()
-
- return res
-
- return fn
-
- def get_cache_hook(self):
- return CacheHook(self)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/registry.py b/lmms-eval-0.2.0.post1/lmms_eval/api/registry.py
deleted file mode 100644
index 6b911997a7044f8ea38560d250ce7080e065af46..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/registry.py
+++ /dev/null
@@ -1,156 +0,0 @@
-from lmms_eval.api.model import lmms
-
-from typing import Callable, Dict
-import evaluate as hf_evaluate
-
-from loguru import logger as eval_logger
-
-MODEL_REGISTRY = {}
-
-
-def register_model(*names):
- # either pass a list or a single alias.
- # function receives them as a tuple of strings
-
- def decorate(cls):
- for name in names:
- assert issubclass(cls, lmms), f"Model '{name}' ({cls.__name__}) must extend lmms class"
-
- assert name not in MODEL_REGISTRY, f"Model named '{name}' conflicts with existing model! Please register with a non-conflicting alias instead."
-
- MODEL_REGISTRY[name] = cls
- return cls
-
- return decorate
-
-
-def get_model(model_name):
- try:
- return MODEL_REGISTRY[model_name]
- except KeyError:
- raise ValueError(f"Attempted to load model '{model_name}', but no model for this name found! Supported model names: {', '.join(MODEL_REGISTRY.keys())}")
-
-
-TASK_REGISTRY = {} # Key: task name, Value: task ConfigurableTask class
-GROUP_REGISTRY = {} # Key: group name, Value: list of task names or group names
-ALL_TASKS = set() # Set of all task names and group names
-func2task_index = {} # Key: task ConfigurableTask class, Value: task name
-
-
-def register_task(name):
- def decorate(fn):
- assert name not in TASK_REGISTRY, f"task named '{name}' conflicts with existing registered task!"
-
- TASK_REGISTRY[name] = fn
- ALL_TASKS.add(name)
- func2task_index[fn.__name__] = name
- return fn
-
- return decorate
-
-
-def register_group(name):
- def decorate(fn):
- func_name = func2task_index[fn.__name__]
- if name in GROUP_REGISTRY:
- GROUP_REGISTRY[name].append(func_name)
- else:
- GROUP_REGISTRY[name] = [func_name]
- ALL_TASKS.add(name)
- return fn
-
- return decorate
-
-
-OUTPUT_TYPE_REGISTRY = {}
-METRIC_REGISTRY = {}
-METRIC_AGGREGATION_REGISTRY = {}
-AGGREGATION_REGISTRY = {}
-HIGHER_IS_BETTER_REGISTRY = {}
-
-DEFAULT_METRIC_REGISTRY = {
- "loglikelihood": [
- "perplexity",
- "acc",
- ],
- "multiple_choice": ["acc", "acc_norm"],
- "generate_until": ["exact_match"],
-}
-
-
-def register_metric(**args):
- # TODO: do we want to enforce a certain interface to registered metrics?
- def decorate(fn):
- assert "metric" in args
- name = args["metric"]
-
- for key, registry in [
- ("metric", METRIC_REGISTRY),
- ("higher_is_better", HIGHER_IS_BETTER_REGISTRY),
- ("aggregation", METRIC_AGGREGATION_REGISTRY),
- ]:
- if key in args:
- value = args[key]
- assert value not in registry, f"{key} named '{value}' conflicts with existing registered {key}!"
-
- if key == "metric":
- registry[name] = fn
- elif key == "aggregation":
- registry[name] = AGGREGATION_REGISTRY[value]
- else:
- registry[name] = value
-
- return fn
-
- return decorate
-
-
-def get_metric(name: str, hf_evaluate_metric=False) -> Callable:
- if not hf_evaluate_metric:
- if name in METRIC_REGISTRY:
- return METRIC_REGISTRY[name]
- else:
- eval_logger.warning(f"Could not find registered metric '{name}' in lm-eval, searching in HF Evaluate library...")
-
- try:
- metric_object = hf_evaluate.load(name)
- return metric_object.compute
- except Exception:
- eval_logger.error(
- f"{name} not found in the evaluate library! Please check https://huggingface.co/evaluate-metric",
- )
-
-
-def register_aggregation(name):
- def decorate(fn):
- assert name not in AGGREGATION_REGISTRY, f"aggregation named '{name}' conflicts with existing registered aggregation!"
-
- AGGREGATION_REGISTRY[name] = fn
- return fn
-
- return decorate
-
-
-def get_aggregation(name):
- try:
- return AGGREGATION_REGISTRY[name]
- except KeyError:
- eval_logger.warning(
- "{} not a registered aggregation metric!".format(name),
- )
-
-
-def get_metric_aggregation(name):
- try:
- return METRIC_AGGREGATION_REGISTRY[name]
- except KeyError:
- eval_logger.warning(
- "{} metric is not assigned a default aggregation!".format(name),
- )
-
-
-def is_higher_better(metric_name):
- try:
- return HIGHER_IS_BETTER_REGISTRY[metric_name]
- except KeyError:
- eval_logger.warning(f"higher_is_better not specified for metric '{metric_name}'!")
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/samplers.py b/lmms-eval-0.2.0.post1/lmms_eval/api/samplers.py
deleted file mode 100644
index f77065e8e53b377fcf30acbc91fcc4bc2f05f9fd..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/samplers.py
+++ /dev/null
@@ -1,94 +0,0 @@
-class ContextSampler:
- def __init__(self, docs, task, fewshot_indices=None, rnd=None) -> None:
- self.rnd = rnd
- assert self.rnd, "must pass rnd to FewShotSampler!"
-
- self.task = task
- self.config = task._config
-
- self.target_delimiter = self.config.target_delimiter
- self.fewshot_delimiter = self.config.fewshot_delimiter
-
- self.doc_to_text = self.task.doc_to_text
- self.doc_to_target = self.task.doc_to_target
- self.doc_to_choice = self.task.doc_to_choice
-
- self.docs = docs # HF dataset split, provided by task._fewshot_docs()
- if fewshot_indices: # subset few-shot docs from
- self.docs = self.docs.select(fewshot_indices)
-
- def get_context(self, doc, num_fewshot):
- # draw an extra fewshot sample if using same split as evaluating on
- n_samples = num_fewshot + 1 if self.config.fewshot_split == self.config.test_split else num_fewshot
-
- # draw `n_samples` docs from fewshot_docs
- fewshotex = self.sample(n_samples)
-
- # get rid of the doc that's the one we're evaluating, if it's in the fewshot
- # TODO: should we just stop people from using fewshot from same split as evaluating?
- selected_docs = [x for x in fewshotex if x != doc][:num_fewshot]
-
- labeled_examples = (
- self.fewshot_delimiter.join(
- [
- # TODO: is separating doc_to_text and doc_to_target by one space always desired?
- (self.doc_to_text(doc) if (self.config.doc_to_choice is None or type(self.doc_to_text(doc)) is str) else self.doc_to_choice(doc)[self.doc_to_text(doc)])
- + self.target_delimiter
- + (
- str(self.doc_to_target(doc)[0])
- if type(self.doc_to_target(doc)) is list
- else self.doc_to_target(doc) if (self.config.doc_to_choice is None or type(self.doc_to_target(doc)) is str) else str(self.doc_to_choice(doc)[self.doc_to_target(doc)])
- )
- for doc in selected_docs
- ]
- )
- + self.fewshot_delimiter
- )
-
- return labeled_examples
-
- def sample(self, n):
- """
- Draw `n` samples from our fewshot docs. This method should be overridden by subclasses.
- """
-
- return self.rnd.sample(self.docs, n)
-
-
-class FirstNSampler(ContextSampler):
- def sample(self, n) -> None:
- """
- Draw the first `n` samples in order from the specified split.
- Used for tasks with "canonical" ordered fewshot examples, such as MMLU and CMMLU.
- """
- assert n <= len(self.docs), f"Error: number of fewshot samples requested exceeds the {len(self.docs)} that are available."
- return self.docs[:n]
-
-
-class BalancedSampler(ContextSampler):
- def sample(self, n) -> None:
- """
- TODO: this should return approximately class-balanced samples from our fewshot examples.
- TODO: what order should they be in? maybe random?
- """
-
- pass
-
-
-class ManualSampler(ContextSampler):
- def sample(self, n) -> None:
- """ """
- pass
-
-
-SAMPLER_REGISTRY = {
- "default": ContextSampler,
- "first_n": FirstNSampler,
-}
-
-
-def get_sampler(name):
- try:
- return SAMPLER_REGISTRY[name]
- except KeyError:
- raise ValueError(f"Attempted to use contextsampler '{name}', but no sampling strategy for this name found! Supported model names: {', '.join(SAMPLER_REGISTRY.keys())}")
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/api/task.py b/lmms-eval-0.2.0.post1/lmms_eval/api/task.py
deleted file mode 100644
index 5560745c0b684bc36ed4f0f1611afecac8af43c8..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/api/task.py
+++ /dev/null
@@ -1,1297 +0,0 @@
-import abc
-import ast
-import itertools
-import json
-
-import os
-import random
-import re
-import shutil
-import subprocess
-from collections.abc import Callable
-from dataclasses import dataclass, field, asdict
-from glob import glob
-from typing import Any, List, Union
-
-import datasets
-import numpy as np
-from PIL import ImageFile
-from datasets import DownloadConfig, Image, Sequence
-from huggingface_hub import snapshot_download
-from tenacity import retry, stop_after_attempt, wait_fixed, stop_after_delay
-from tqdm import tqdm
-
-from accelerate import Accelerator
-from lmms_eval import utils
-from lmms_eval.api import samplers
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.registry import (
- AGGREGATION_REGISTRY,
- DEFAULT_METRIC_REGISTRY,
- METRIC_REGISTRY,
- OUTPUT_TYPE_REGISTRY,
- get_aggregation,
- get_metric,
- get_metric_aggregation,
- is_higher_better,
-)
-from lmms_eval.filters import build_filter_ensemble
-
-from loguru import logger as eval_logger
-
-# HuggingfaceM4/NoCaps contains truncated image in test split
-# Include this inside code block to avoid error
-ImageFile.LOAD_TRUNCATED_IMAGES = True
-
-ALL_OUTPUT_TYPES = [
- "loglikelihood",
- "multiple_choice",
- "generate_until",
-]
-
-
-@dataclass
-class TaskConfig(dict):
- # task naming/registry
- task: str = None
- task_alias: str = None
- group: Union[str, list] = None
- group_alias: Union[str, list] = None
- # HF dataset options.
- # which dataset to use,
- # and what splits for what purpose
- dataset_path: str = None
- dataset_name: str = None
- dataset_kwargs: dict = None
- training_split: str = None
- validation_split: str = None
- test_split: str = None
- fewshot_split: str = None # TODO: assert that this not None if num_fewshot > 0. (?) assert if this is same split as one evaling (?)
- # formatting / prompting options.
- # see docs/advanced_task_guide.md for more info
- process_docs: Callable = None
- doc_to_visual: Union[Callable, str] = None
- doc_to_text: Union[Callable, str] = None
- doc_to_target: Union[Callable, str] = None
- doc_to_choice: Union[Callable, str, dict, list] = None
- process_results: Union[Callable, str] = None
- use_prompt: str = None
- description: str = ""
- target_delimiter: str = " "
- fewshot_delimiter: str = "\n\n"
- fewshot_config: dict = None
- # runtime configuration options
- num_fewshot: int = None
- # scoring options
- metric_list: list = None
- output_type: str = "generate_until"
- generation_kwargs: dict = None
- repeats: int = 1
- filter_list: Union[str, list] = None
- should_decontaminate: bool = False
- doc_to_decontamination_query: str = None
-
- metadata: Union[str, list] = None # by default, not used in the code. allows for users to pass arbitrary info to tasks
-
- model_specific_prompt_kwargs: dict = None
- model_specific_generation_kwargs: dict = None
- model_specific_target_kwargs: dict = None
-
- def __post_init__(self) -> None:
- if self.dataset_path and os.path.exists(os.path.dirname(self.dataset_path)):
- import inspect
- from importlib import import_module
-
- # self.dataset_path = inspect.getfile(import_module(self.dataset_path))
-
- if self.generation_kwargs is not None:
- if self.output_type != "generate_until":
- eval_logger.warning(f"[{self.task}] passed `generation_kwargs`, but not using `output_type: generate_until`!")
- assert self.output_type != "generate_until"
-
- if "temperature" in self.generation_kwargs:
- self.generation_kwargs["temperature"] = float(self.generation_kwargs["temperature"])
-
- if "until" not in self.generation_kwargs:
- self.generation_kwargs["until"] = [self.fewshot_delimiter]
- else:
- if self.output_type == "generate_until":
- # ensure that we greedily generate in absence of explicit arguments otherwise
- self.generation_kwargs = {
- "until": None if self.fewshot_delimiter is None else [self.fewshot_delimiter],
- "do_sample": False,
- }
-
- # TODO: how to make TaskConfigs be de- and re-serializable, even when using the !function constructor?
-
- def __getitem__(self, item):
- return getattr(self, item)
-
- def __setitem__(self, item, value):
- return setattr(self, item, value)
-
- def to_dict(self):
- """dumps the current config as a dictionary object, as a printable format.
- null fields will not be printed.
- Used for dumping results alongside full task configuration
-
- :return: dict
- A printable dictionary version of the TaskConfig object.
-
- # TODO: should any default value in the TaskConfig not be printed?
- """
- cfg_dict = asdict(self)
- # remove values that are `None`
- for k, v in list(cfg_dict.items()):
- if v is None:
- cfg_dict.pop(k)
- elif isinstance(v, Callable):
- # TODO: this should handle Promptsource template objects as a separate case?
- cfg_dict[k] = str(v)
- return cfg_dict
-
-
-class Task(abc.ABC):
- """A task represents an entire benchmark including its dataset, problems,
- answers, and evaluation methods. See BoolQ for a simple example implementation
-
- A `doc` can be any python object which represents one instance of evaluation.
- This is usually a dictionary e.g.
- {"question": ..., "answer": ...} or
- {"question": ..., question, answer)
- """
-
- VERSION = None
-
- # The name of the `Task` benchmark as denoted in the HuggingFace datasets Hub
- # or a path to a custom `datasets` loading script.
- DATASET_PATH: str = None
-
- # The name of a subset within `DATASET_PATH`.
- DATASET_NAME: str = None
-
- OUTPUT_TYPE: str = None
-
- def __init__(
- self,
- data_dir=None,
- cache_dir=None,
- download_mode=None,
- config=None,
- ) -> None:
- """
- :param data_dir: str
- Stores the path to a local folder containing the `Task`'s data files.
- Use this to specify the path to manually downloaded data (usually when
- the dataset is not publicly accessible).
- :param cache_dir: str
- The directory to read/write the `Task` dataset. This follows the
- HuggingFace `datasets` API with the default cache directory located at:
- `~/.cache/huggingface/datasets`
- NOTE: You can change the cache location globally for a given process
- to another directory:
- `export HF_DATASETS_CACHE="/path/to/another/directory"`
- :param download_mode: datasets.DownloadMode
- How to treat pre-existing `Task` downloads and data.
- - `datasets.DownloadMode.REUSE_DATASET_IF_EXISTS`
- Reuse download and reuse dataset.
- - `datasets.DownloadMode.REUSE_CACHE_IF_EXISTS`
- Reuse download with fresh dataset.
- - `datasets.DownloadMode.FORCE_REDOWNLOAD`
- Fresh download and fresh dataset.
- """
- self.download(data_dir, cache_dir, download_mode)
- self._training_docs = None
- self._fewshot_docs = None
- self._instances = None
-
- self._config = TaskConfig({**config}) if config else TaskConfig()
-
- self._filters = [build_filter_ensemble("none", [["take_first", None]])]
-
- def download(self, data_dir=None, cache_dir=None, download_mode=None) -> None:
- """Downloads and returns the task dataset.
- Override this method to download the dataset from a custom API.
-
- :param data_dir: str
- Stores the path to a local folder containing the `Task`'s data files.
- Use this to specify the path to manually downloaded data (usually when
- the dataset is not publicly accessible).
- :param cache_dir: str
- The directory to read/write the `Task` dataset. This follows the
- HuggingFace `datasets` API with the default cache directory located at:
- `~/.cache/huggingface/datasets`
- NOTE: You can change the cache location globally for a given process
- by setting the shell environment variable, `HF_DATASETS_CACHE`,
- to another directory:
- `export HF_DATASETS_CACHE="/path/to/another/directory"`
- :param download_mode: datasets.DownloadMode
- How to treat pre-existing `Task` downloads and data.
- - `datasets.DownloadMode.REUSE_DATASET_IF_EXISTS`
- Reuse download and reuse dataset.
- - `datasets.DownloadMode.REUSE_CACHE_IF_EXISTS`
- Reuse download with fresh dataset.
- - `datasets.DownloadMode.FORCE_REDOWNLOAD`
- Fresh download and fresh dataset.
- """
- self.dataset = datasets.load_dataset(
- path=self.DATASET_PATH,
- name=self.DATASET_NAME,
- data_dir=data_dir,
- cache_dir=cache_dir,
- download_mode=download_mode,
- )
- self.dataset_no_image = datasets.load_dataset(
- path=self.DATASET_PATH,
- name=self.DATASET_NAME,
- data_dir=data_dir,
- cache_dir=cache_dir,
- download_mode=download_mode,
- )
- for doc_name in self.dataset_no_image:
- remove_cols = []
- features = self.dataset_no_image[doc_name].features
- # If it is an Image instance or a Sequence of Image instance. Remove it
- for feature in features:
- if isinstance(features[feature], Image):
- remove_cols.append(feature)
- elif isinstance(features[feature], Sequence) and isinstance(features[feature].feature, Image):
- remove_cols.append(feature)
- for remove_col in remove_cols:
- self.dataset_no_image[doc_name] = self.dataset_no_image[doc_name].remove_columns(remove_col)
-
- @property
- def config(self):
- """Returns the TaskConfig associated with this class."""
- return self._config
-
- @abc.abstractmethod
- def has_training_docs(self):
- """Whether the task has a training set"""
- pass
-
- @abc.abstractmethod
- def has_validation_docs(self):
- """Whether the task has a validation set"""
- pass
-
- @abc.abstractmethod
- def has_test_docs(self):
- """Whether the task has a test set"""
- pass
-
- def training_docs(self):
- """
- :return: Iterable[obj]
- A iterable of any object, that doc_to_text can handle
- """
- return []
-
- def validation_docs(self):
- """
- :return: Iterable[obj]
- A iterable of any object, that doc_to_text can handle
- """
- return []
-
- def test_docs(self):
- """
- :return: Iterable[obj]
- A iterable of any object, that doc_to_text can handle
- """
- return []
-
- def fewshot_docs(self):
- """
- :return: Iterable[obj]
- A iterable of any object, that doc_to_text can handle
- """
- if self.has_training_docs():
- return self.training_docs()
- elif self.has_validation_docs():
- return self.validation_docs()
- else:
- if self.config.num_fewshot is not None:
- eval_logger.warning("has_training_docs and has_validation_docs are False" ", using test_docs as fewshot_docs but this is not recommended.")
- return self.test_docs()
-
- def _process_doc(self, doc):
- """
- Override this to process (detokenize, strip, replace, etc.) individual
- documents. This can be used in a map over documents of a data split.
- E.g. `map(self._process_doc, self.dataset["validation"])`
-
- :return: dict
- The processed version of the specified `doc`.
- """
- return doc
-
- @property
- def instances(self):
- """After calling `task.build_all_requests()`, tasks
- maintain a list of the dataset instances which will be evaluated.
- """
- return self._instances
-
- def fewshot_examples(self, k, rnd):
- if self._training_docs is None:
- self._training_docs = list(self.training_docs())
-
- return rnd.sample(self._training_docs, k)
-
- def doc_to_decontamination_query(self, doc) -> None:
- print("Override doc_to_decontamination_query with document specific decontamination query.")
- assert False
-
- @abc.abstractmethod
- def doc_to_text(self, doc):
- pass
-
- @abc.abstractmethod
- def doc_to_target(self, doc):
- pass
-
- # @profile
- def build_all_requests(self, limit=None, rank=None, world_size=None) -> None:
- """Build a set of Instances for a task, and store them in task.instances"""
- if self.has_test_docs():
- docs = self.test_docs()
- split = self.config.test_split
- elif self.has_validation_docs():
- docs = self.validation_docs()
- split = self.config.validation_split
- else:
- assert False, f"Task dataset (path={self.DATASET_PATH}, name={self.DATASET_NAME}) must have valid or test docs!"
-
- eval_logger.info(f"Building contexts for task {self.CONFIG.task} on rank {rank}...")
- instances = []
- doc_id_iterator = utils.create_iterator([i for i in range(len(docs))], rank, world_size, limit)
- doc_id_iterator, doc_id_iterator_counting = itertools.tee(doc_id_iterator)
- total_docs = sum(1 for _ in doc_id_iterator_counting)
- pbar = tqdm(total=total_docs, desc=f"Building context", disable=(rank != 0))
- for doc_id in doc_id_iterator:
- # sample fewshot context #TODO: need to offset doc_id by rank now!
- fewshot_ctx = self.fewshot_context(doc_id, 0 if self.config.num_fewshot is None else self.config.num_fewshot, self.config.training_split if self.has_training_docs() else split)
-
- # TODO: we should override self.config.repeats if doing greedy gen so users don't waste time+compute
- inst = self.construct_requests(doc_id=doc_id, ctx=fewshot_ctx, metadata=(self.config["task"], doc_id, self.config.repeats), split=split)
-
- if not isinstance(inst, list):
- inst = [inst]
-
- instances.extend(inst)
- pbar.update(1)
-
- pbar.close()
- self._instances = instances
- assert len(self._instances) != 0, "task.build_requests() did not find any docs!"
-
- @abc.abstractmethod
- def construct_requests(self, doc_id, ctx, **kwargs):
- """Uses RequestFactory to construct Requests and returns an iterable of
- Requests which will be sent to the LMM.
-
- :param doc_id: int
- The index of a document within `self.test_docs()` or `self.validation_docs()`,
- whichever is the main split used.
- :param ctx: str
- The context string, generated by fewshot_context. This includes the natural
- language description, as well as the few shot examples, and the question
- part of the document for `doc`.
- :param repeats: int
- TODO: update this docstring
- The number of times each instance in a dataset is inferred on. Defaults to 1,
- can be increased for techniques like majority voting.
- """
- pass
-
- @abc.abstractmethod
- def process_results(self, doc, results):
- """Take a single document and the LMM results and evaluates, returning a
- dict where keys are the names of submetrics and values are the values of
- the metric for that one document
-
- :param doc:
- The document as returned from training_docs, validation_docs, or test_docs.
- :param results:
- The results of the requests created in construct_requests.
- """
- pass
-
- @abc.abstractmethod
- def aggregation(self):
- """
- :returns: {str: [metric_score] -> float}
- A dictionary where keys are the names of submetrics and values are
- functions that aggregate a list of metric scores
- """
- pass
-
- @abc.abstractmethod
- def higher_is_better(self):
- """
- :returns: {str: bool}
- A dictionary where keys are the names of submetrics and values are
- whether a higher value of the submetric is better
- """
- pass
-
- @classmethod
- def count_bytes(cls, doc):
- """Used for byte-level perplexity metrics in rolling loglikelihood"""
- return len(doc.encode("utf-8"))
-
- @utils.positional_deprecated
- def fewshot_context(
- self,
- doc_id,
- num_fewshot,
- split,
- rnd=random.Random(1234),
- description=None,
- ):
- """Returns a fewshot context string that is made up of a prepended description
- (if provided), the `num_fewshot` number of examples, and an appended prompt example.
-
- :param doc_id: int
- The document id as returned from training_docs, validation_docs, or test_docs.
- :param num_fewshot: int
- The number of fewshot examples to provide in the returned context string.
- :param split: str
- The split of the document to retrieve from the dataset
- :param rnd: random.Random
- The pseudo-random number generator used to randomly sample examples.
- WARNING: This is currently a required arg although it's optionalized with a default `None`.
- :param description: str
- The task's description that will be prepended to the fewshot examples.
- :returns: str
- The fewshot context.
- """
- assert rnd is not None, "A `random.Random` generator argument must be provided to `rnd`"
-
- description = description if description else ""
- doc = self.dataset_no_image[split][doc_id]
-
- if num_fewshot == 0:
- labeled_examples = ""
- else:
- # for sets with no training docs, draw from other set *but ensure no overlap with current doc*
- if self.has_training_docs():
- fewshotex = self.fewshot_examples(k=num_fewshot, rnd=rnd)
- else:
- if self._fewshot_docs is None:
- self._fewshot_docs = list(self.validation_docs() if self.has_validation_docs() else self.test_docs())
-
- fewshotex = rnd.sample(self._fewshot_docs, num_fewshot + 1)
-
- # get rid of the doc that's the one we're evaluating, if it's in the fewshot
- fewshotex = [x for x in fewshotex if x != doc][:num_fewshot]
-
- labeled_examples = "\n\n".join([self.doc_to_text(doc) + self.doc_to_target(doc) for doc in fewshotex]) + "\n\n"
-
- example = self.doc_to_text(doc)
- return description + labeled_examples + example
-
- def apply_filters(self):
- if hasattr(self, "_filters"):
- for f in self._filters:
- f.apply(self._instances, None)
- else:
- eval_logger.warning("No filter defined, passing through instances")
- return self._instances
-
- def dump_config(self) -> dict:
- """Returns a dictionary representing the task's config.
-
- :returns: str
- The fewshot context.
- """
- # TODO: this should only return the overrides applied to a non-YAML task's configuration.
- # (num_fewshot)
- return self.config.to_dict()
-
- def override_metric(self, metric_name: str) -> None:
- """
- Override the default metrics used for evaluation with custom metrics.
-
- Parameters:
- - metric_name (str): The name of the custom metric to override. Should be registered in api.metrics.
- """
- (
- self._metric_fn_list,
- self._aggregation_list,
- self._metric_fn_kwargs,
- self._higher_is_better,
- ) = ({}, {}, {}, {})
- self._metric_fn_list[metric_name] = get_metric(metric_name)
- self._aggregation_list[metric_name] = get_metric_aggregation(metric_name)
- self._higher_is_better[metric_name] = is_higher_better(metric_name)
- self._metric_fn_kwargs[metric_name] = {}
- if not isinstance(self, ConfigurableTask):
- self.process_results = lambda x, y: {metric_name: get_metric(metric_name)}
- self.aggregation = lambda: {metric_name: get_metric_aggregation(metric_name)}
- setattr(self._config, "metric_list", [{"metric": metric_name}])
- setattr(self._config, "process_results", None)
-
-
-class ConfigurableTask(Task):
- VERSION = "Yaml"
- OUTPUT_TYPE = None
- CONFIG = None
-
- def __init__(self, model_name) -> None: # TODO no super() call here
- # Get pre-configured attributes
- self._config = self.CONFIG
- # different model requires different prompt, we have to take those into account.
-
- self.model_name = model_name
- self._prepare_model_specific_config()
-
- assert self.config.output_type in ALL_OUTPUT_TYPES
- self.OUTPUT_TYPE = self.config.output_type
-
- self.DATASET_PATH = self.config.dataset_path
-
- if self.config.dataset_name is not None:
- self.DATASET_NAME = self.config.dataset_name
-
- self._prepare_metric_and_aggregation()
-
- self.download(self.config.dataset_kwargs)
- self._training_docs = None
- self._fewshot_docs = None
-
- if self.config.filter_list is not None:
- self._filters = []
- for filter_config in self.config.filter_list:
- for filter_pipeline in filter_config:
- filter_name = filter_config["name"]
- filter_functions = filter_config["filter"]
- components = []
- for function in filter_functions:
- kwargs = {key: function[key] for key in function if key != "function"}
- components.append([function["function"], kwargs])
- filter_pipeline = build_filter_ensemble(filter_name, components)
- self._filters.append(filter_pipeline)
- else:
- self._filters = [build_filter_ensemble("none", [["take_first", None]])]
- if self.config.fewshot_config is not None:
- self.sampler = samplers.get_sampler(self.config.fewshot_config.get("sampler", "default") if self.config.fewshot_config else "default")(list(self.fewshot_docs()), self, rnd=random.Random(1234))
-
- if self.has_test_docs():
- self.task_docs = self.test_docs()
- elif self.has_validation_docs():
- self.task_docs = self.validation_docs()
- else:
- assert False, f"Task dataset (path={self.DATASET_PATH}, name={self.DATASET_NAME}) must have valid or test docs!"
-
- # Test One Doc
- self.features = list(self.task_docs.features.keys())
- self.multiple_input = 0
- self.multiple_target = 0
- test_doc = self.task_docs[0]
- test_text = self.doc_to_text(test_doc)
- test_target = self.doc_to_target(test_doc)
-
- if self.config.doc_to_choice is not None:
- test_choice = self.doc_to_choice(test_doc)
- if type(test_choice) is not list:
- eval_logger.error("doc_to_choice must return list")
- else:
- num_choice = len(test_choice)
-
- if type(test_text) is int:
- self.multiple_input = num_choice
- else:
- test_choice = None
-
- if type(test_target) is list:
- self.multiple_target = len(test_target)
- else:
- if (type(test_target) is int) and (test_choice is not None):
- test_target = test_choice[test_target]
- else:
- test_target = str(test_target)
-
- if test_choice is not None:
- check_choices = test_choice
- else:
- check_choices = [test_target]
- if self.config.doc_to_choice is not None:
- for choice in check_choices:
- choice_has_whitespace = True if choice[0].isspace() else False
- delimiter_has_whitespace = True if self.config.target_delimiter.rstrip() != self.config.target_delimiter else False
-
- if delimiter_has_whitespace and choice_has_whitespace:
- eval_logger.warning(f'Both target_delimiter and target choice: "{choice}" have whitespace')
- elif (not delimiter_has_whitespace) and (not choice_has_whitespace):
- eval_logger.warning(f'Both target_delimiter "{self.config.target_delimiter}" and target choice: "{choice}" do not have whitespace, ignore if the language you are evaluating on does not require/use whitespace')
-
- def _prepare_model_specific_config(self):
- self.model_specific_prompt_kwargs = self.config.model_specific_prompt_kwargs
- if self.model_specific_prompt_kwargs is not None:
- if self.model_name in self.model_specific_prompt_kwargs:
- self.model_specific_prompt_kwargs = self.model_specific_prompt_kwargs[self.model_name]
- else:
- self.model_specific_prompt_kwargs = self.model_specific_prompt_kwargs.get("default", None)
-
- self.model_specific_target_kwargs = self.config.model_specific_target_kwargs
- if self.model_specific_target_kwargs is not None:
- if self.model_name in self.model_specific_target_kwargs:
- self.model_specific_target_kwargs = self.model_specific_target_kwargs[self.model_name]
- else:
- self.model_specific_target_kwargs = self.model_specific_target_kwargs.get("default", None)
- self.model_specific_generation_kwargs = self.config.model_specific_generation_kwargs
- if self.model_specific_generation_kwargs is not None:
- if self.model_name in self.model_specific_generation_kwargs:
- self.model_specific_generation_kwargs = self.model_specific_generation_kwargs[self.model_name]
- else:
- self.model_specific_generation_kwargs = self.model_specific_generation_kwargs.get("default", {})
-
- self.config.generation_kwargs.update(self.model_specific_generation_kwargs)
-
- def _prepare_metric_and_aggregation(self):
- self._metric_fn_list = {}
- self._metric_fn_kwargs = {}
- self._aggregation_list = {}
- self._higher_is_better = {}
-
- if self.config.metric_list is None:
- # TODO: handle this in TaskConfig.__post_init__ ?
- _metric_list = DEFAULT_METRIC_REGISTRY[self.config.output_type]
-
- for metric_name in _metric_list:
- self._metric_fn_list[metric_name] = METRIC_REGISTRY[metric_name]
- self._metric_fn_kwargs[metric_name] = {}
- self._aggregation_list[metric_name] = get_metric_aggregation(metric_name)
- self._higher_is_better[metric_name] = is_higher_better(metric_name)
- else:
- for metric_config in self.config.metric_list:
- assert "metric" in metric_config
- metric_name = metric_config["metric"]
- kwargs = {key: metric_config[key] for key in metric_config if key not in ["metric", "aggregation", "higher_is_better"]}
-
- if self.config.process_results is not None:
- self._metric_fn_list[metric_name] = None
- self._metric_fn_kwargs[metric_name] = {}
- elif callable(metric_name):
- metric_fn = metric_name.__call__
- metric_name = metric_name.__name__
- self._metric_fn_list[metric_name] = metric_fn
- self._metric_fn_kwargs[metric_name] = kwargs
- else:
- self._metric_fn_list[metric_name] = METRIC_REGISTRY[metric_name]
- self._metric_fn_kwargs[metric_name] = kwargs
-
- if "aggregation" in metric_config:
- agg_name = metric_config["aggregation"]
- if type(agg_name) == str:
- self._aggregation_list[metric_name] = get_aggregation(agg_name)
- elif callable(agg_name):
- self._aggregation_list[metric_name] = metric_config["aggregation"]
- else:
- INV_AGG_REGISTRY = {v: k for k, v in AGGREGATION_REGISTRY.items()}
- metric_agg = get_metric_aggregation(metric_name)
- eval_logger.warning(f"[Task: {self._config.task}] metric {metric_name} is defined, but aggregation is not. " f"using default " f"aggregation={INV_AGG_REGISTRY[metric_agg]}")
- self._aggregation_list[metric_name] = metric_agg
-
- if "higher_is_better" in metric_config:
- self._higher_is_better[metric_name] = metric_config["higher_is_better"]
- else:
- eval_logger.warning(f"[Task: {self._config.task}] metric {metric_name} is defined, but higher_is_better is not. " f"using default " f"higher_is_better={is_higher_better(metric_name)}")
- self._higher_is_better[metric_name] = is_higher_better(metric_name)
-
- @retry(stop=(stop_after_attempt(5) | stop_after_delay(60)), wait=wait_fixed(2))
- def download(self, dataset_kwargs=None) -> None:
- # If the dataset is a video dataset,
- # Recursively search whether their is a zip and unzip it to the huggingface home
- download_config = DownloadConfig()
- download_config.max_retries = dataset_kwargs.get("max_retries", 10) if dataset_kwargs is not None else 10
- download_config.num_proc = dataset_kwargs.get("num_proc", 8) if dataset_kwargs is not None else 8
- download_config.local_files_only = dataset_kwargs.get("local_files_only", False) if dataset_kwargs is not None else False
- if dataset_kwargs is not None:
- if "From_YouTube" in dataset_kwargs:
-
- def _download_from_youtube(path):
- try:
- for video in tqdm(self.all_dataset[split]):
- video_id = video["videoID"]
- target_path = os.path.join(path, f"{video_id}.mp4")
- assert shutil.which("yt-dlp") is not None, "yt-dlp must be installed and available in the system's PATH"
- command = f"yt-dlp -o {target_path} -f mp4 https://www.youtube.com/watch?v={video_id}"
- subprocess.run(command, shell=True)
- with open(os.path.join(cache_path, f"{task}_download_status.json"), "w") as f:
- f.write(json.dumps({task: "downloaded"}))
- except Exception as e:
- eval_logger.error(f"Error while downloading {task} data: {e}")
- with open(os.path.join(cache_path, f"{task}_download_status.json"), "w") as f:
- f.write(json.dumps({task: "not downloaded"}))
-
- hf_home = os.getenv("HF_HOME", "~/.cache/huggingface/")
- accelerator = Accelerator()
- if accelerator.is_main_process:
- dataset_kwargs.pop("From_YouTube")
- self.all_dataset = datasets.load_dataset(
- path=self.DATASET_PATH,
- name=self.DATASET_NAME,
- download_mode=datasets.DownloadMode.REUSE_DATASET_IF_EXISTS,
- **dataset_kwargs if dataset_kwargs is not None else {},
- )
- dataset_kwargs["From_YouTube"] = True
- cache_path = snapshot_download(repo_id=self.DATASET_PATH, repo_type="dataset") # download_parquet
- split = vars(self.config)["test_split"]
- task = vars(self.config)["task"]
-
- video_path = os.path.join(hf_home, task)
- if os.path.exists(os.path.join(cache_path, f"{task}_download_status.json")):
- download_status = json.load(open(os.path.join(cache_path, f"{task}_download_status.json"), "r"))
- if download_status[task] == "downloaded":
- eval_logger.info(f"Data for {task} already download!")
- else:
- eval_logger.info(f"Start downloading YouTube data to {video_path}...")
- _download_from_youtube(video_path)
- else:
- eval_logger.info(f"Start downloading YouTube data to {video_path}...")
- _download_from_youtube(video_path)
-
- accelerator.wait_for_everyone()
- if "builder_script" in dataset_kwargs:
- builder_script = dataset_kwargs["builder_script"]
- self.DATASET_PATH = os.path.join(cache_path, builder_script)
- dataset_kwargs.pop("builder_script")
-
- downloaded_video_ids = [i.split(".mp4")[0] for i in os.listdir(os.path.expanduser(video_path)) if i.endswith(".mp4")]
- # Filtered the existing dataset with the downloaded video ids
- self.dataset = datasets.DatasetDict({split: self.all_dataset[split].filter(lambda x: x["videoID"] in downloaded_video_ids)})
-
- self.dataset_no_image = self.dataset
- dataset_kwargs.pop("From_YouTube")
- return
-
- if "video" in dataset_kwargs and dataset_kwargs["video"]:
- hf_home = os.getenv("HF_HOME", "~/.cache/huggingface/")
- cache_dir = dataset_kwargs["cache_dir"]
- cache_dir = os.path.join(hf_home, cache_dir)
- accelerator = Accelerator()
- if accelerator.is_main_process:
- force_download = dataset_kwargs.get("force_download", False)
- force_unzip = dataset_kwargs.get("force_unzip", False)
- cache_path = snapshot_download(repo_id=self.DATASET_PATH, repo_type="dataset", force_download=force_download, etag_timeout=60)
- zip_files = glob(os.path.join(cache_path, "**/*.zip"), recursive=True)
- tar_files = glob(os.path.join(cache_path, "**/*.tar*"), recursive=True)
-
- def unzip_video_data(zip_file):
- import zipfile
-
- with zipfile.ZipFile(zip_file, "r") as zip_ref:
- zip_ref.extractall(cache_dir)
- eval_logger.info(f"Extracted all files from {zip_file} to {cache_dir}")
-
- def untar_video_data(tar_file):
- import tarfile
-
- with tarfile.open(tar_file, "r") as tar_ref:
- tar_ref.extractall(cache_dir)
- eval_logger.info(f"Extracted all files from {tar_file} to {cache_dir}")
-
- def concat_tar_parts(tar_parts, output_tar):
- with open(output_tar, "wb") as out_tar:
- from tqdm import tqdm
-
- for part in tqdm(sorted(tar_parts)):
- with open(part, "rb") as part_file:
- out_tar.write(part_file.read())
- eval_logger.info(f"Concatenated parts {tar_parts} into {output_tar}")
-
- # Unzip zip files if needed
- if force_unzip or (not os.path.exists(cache_dir) and len(zip_files) > 0):
- for zip_file in zip_files:
- unzip_video_data(zip_file)
-
- # Concatenate and extract tar files if needed
- if force_unzip or (not os.path.exists(cache_dir) and len(tar_files) > 0):
- tar_parts_dict = {}
-
- # Group tar parts together
- for tar_file in tar_files:
- base_name = tar_file.split(".tar")[0]
- if base_name not in tar_parts_dict:
- tar_parts_dict[base_name] = []
- tar_parts_dict[base_name].append(tar_file)
-
- # Concatenate and untar split parts
- for base_name, parts in tar_parts_dict.items():
- eval_logger.info(f"Extracting following tar files: {parts}")
- output_tar = base_name + ".tar"
- if not os.path.exists(output_tar):
- eval_logger.info(f"Start concatenating tar files")
-
- concat_tar_parts(parts, output_tar)
- eval_logger.info(f"Finish concatenating tar files")
-
- if not os.path.exists(os.path.join(cache_dir, os.path.basename(base_name))):
- untar_video_data(output_tar)
-
- accelerator.wait_for_everyone()
- dataset_kwargs.pop("cache_dir")
- dataset_kwargs.pop("video")
-
- if "builder_script" in dataset_kwargs:
- builder_script = dataset_kwargs["builder_script"]
- self.DATASET_PATH = os.path.join(cache_path, builder_script)
- dataset_kwargs.pop("builder_script")
-
- if "force_download" in dataset_kwargs:
- dataset_kwargs.pop("force_download")
-
- if "force_unzip" in dataset_kwargs:
- dataset_kwargs.pop("force_unzip")
-
- if "local_files_only" in dataset_kwargs:
- dataset_kwargs.pop("local_files_only")
-
- self.dataset = datasets.load_dataset(
- path=self.DATASET_PATH,
- name=self.DATASET_NAME,
- download_mode=datasets.DownloadMode.REUSE_DATASET_IF_EXISTS,
- download_config=download_config,
- **dataset_kwargs if dataset_kwargs is not None else {},
- )
- self.dataset_no_image = datasets.load_dataset(
- path=self.DATASET_PATH,
- name=self.DATASET_NAME,
- download_mode=datasets.DownloadMode.REUSE_DATASET_IF_EXISTS,
- download_config=download_config,
- **dataset_kwargs if dataset_kwargs is not None else {},
- )
- for doc_name in self.dataset_no_image:
- remove_cols = []
- features = self.dataset_no_image[doc_name].features
- # If it is an Image instance or a Sequence of Image instance. Remove it
- for feature in features:
- if isinstance(features[feature], Image):
- remove_cols.append(feature)
- elif isinstance(features[feature], Sequence) and isinstance(features[feature].feature, Image):
- remove_cols.append(feature)
- for remove_col in remove_cols:
- self.dataset_no_image[doc_name] = self.dataset_no_image[doc_name].remove_columns(remove_col)
-
- def has_training_docs(self) -> bool:
- if self.config.training_split is not None:
- return True
- else:
- return False
-
- def has_validation_docs(self) -> bool:
- if self.config.validation_split is not None:
- return True
- else:
- return False
-
- def has_test_docs(self) -> bool:
- if self.config.test_split is not None:
- return True
- else:
- return False
-
- def training_docs(self) -> datasets.Dataset:
- if self.has_training_docs():
- if self.config.process_docs is not None:
- return self.config.process_docs(self.dataset[self.config.training_split])
- return self.dataset[self.config.training_split]
-
- def validation_docs(self) -> datasets.Dataset:
- if self.has_validation_docs():
- if self.config.process_docs is not None:
- return self.config.process_docs(self.dataset[self.config.validation_split])
- return self.dataset[self.config.validation_split]
-
- def test_docs(self) -> datasets.Dataset:
- if self.has_test_docs():
- if self.config.process_docs is not None:
- return self.config.process_docs(self.dataset[self.config.test_split])
- return self.dataset[self.config.test_split]
-
- def fewshot_docs(self):
- if self.config.fewshot_split is not None:
- return self.dataset[self.config.fewshot_split]
- else:
- if (self.config.num_fewshot is not None) and (self.config.num_fewshot > 0):
- eval_logger.warning(f"Task '{self.config.task}': " "num_fewshot > 0 but fewshot_split is None. " "using preconfigured rule.")
- return super().fewshot_docs()
-
- @utils.positional_deprecated
- def fewshot_context(self, doc_id, num_fewshot, split):
- """Returns a fewshot context string that is made up of a prepended description
- (if provided), the `num_fewshot` number of examples, and an appended prompt example.
-
- :param doc_id: str
- The document id as returned from training_docs, validation_docs, or test_docs.
- :param num_fewshot: int
- The number of fewshot examples to provide in the returned context string.
- :returns: str
- The fewshot context.
- """
- doc = self.dataset_no_image[split][doc_id]
- if num_fewshot == 0:
- # always prepend the (possibly empty) task description
- labeled_examples = self.config.description
- else:
- labeled_examples = self.config.description + self.sampler.get_context(doc, num_fewshot)
- example = self.doc_to_text(doc)
- if type(example) == str:
- return labeled_examples + example
- elif type(example) == list:
- return [labeled_examples + ex for ex in example]
- elif type(example) == int:
- if self.config.doc_to_choice is not None:
- choices = self.doc_to_choice(doc)
- return labeled_examples + choices[example]
- else:
- return labeled_examples + str(example)
-
- def apply_filters(self):
- if hasattr(self, "_filters"):
- for f in self._filters:
- f.apply(self._instances, self.task_docs)
- else:
- eval_logger.warning("No filter defined, passing through instances")
- return self._instances
-
- def should_decontaminate(self):
- return self.config.should_decontaminate
-
- def doc_to_decontamination_query(self, doc):
- if self.config.should_decontaminate:
- if self.config.doc_to_decontamination_query is None:
- return self.doc_to_text(doc)
- else:
- doc_to_decontamination_query = self.config.doc_to_decontamination_query
- if doc_to_decontamination_query in self.features:
- return doc[doc_to_decontamination_query]
- elif callable(doc_to_decontamination_query):
- return doc_to_decontamination_query(doc)
- else:
- return ast.literal_eval(utils.apply_template(self.config.doc_to_decontamination_query, doc))
-
- def _process_doc(self, doc):
- """
- Override this to process (detokenize, strip, replace, etc.) individual
- documents. This can be used in a map over documents of a data split.
- E.g. `map(self._process_doc, self.dataset["validation"])`
-
- :return: dict
- The processed version of the specified `doc`.
- """
- return doc
-
- def doc_to_text(self, doc):
- doc_to_text = self.config.doc_to_text
-
- if type(doc_to_text) == int:
- return doc_to_text
- elif type(doc_to_text) == str:
- if doc_to_text in self.features:
- # if self.config.doc_to_choice is not None:
- # return self.doc_to_choice(doc)[doc[doc_to_text]]
- # else:
- return doc[doc_to_text]
- else:
- text_string = utils.apply_template(doc_to_text, doc)
- if text_string.isdigit() and self._config.doc_to_choice is not None:
- return ast.literal_eval(text_string)
- else:
- return text_string
- elif callable(doc_to_text):
- return (
- doc_to_text(doc, self.model_specific_prompt_kwargs)
- if self.model_specific_prompt_kwargs is not None
- else doc_to_text(
- doc,
- )
- )
- # Used when applying a Promptsource template
- elif hasattr(doc_to_text, "apply"):
- applied_prompt = doc_to_text.apply(doc)
- if len(applied_prompt) == 2:
- return applied_prompt[0]
- else:
- eval_logger.warning("Applied prompt returns empty string")
- return self.config.fewshot_delimiter
- else:
- print(type(doc_to_text))
- raise TypeError
-
- def doc_to_target(self, doc: dict) -> Union[int, str, list]:
- doc_to_target = self.config.doc_to_target
-
- if type(doc_to_target) == int:
- return doc_to_target
- elif type(doc_to_target) == str:
- if doc_to_target in self.features:
- # if self.config.doc_to_choice is not None:
- # return self.doc_to_choice(doc)[doc[doc_to_target]]
- # else:
- return doc[doc_to_target]
- else:
- target_string = utils.apply_template(doc_to_target, doc)
- if target_string.isdigit() and self._config.doc_to_choice is not None:
- return ast.literal_eval(target_string)
- elif len(target_string) >= 2 and (target_string[0] == "[") and (target_string[-1] == "]"):
- try:
- return ast.literal_eval(target_string)
- except (SyntaxError, ValueError):
- return target_string
- else:
- return target_string
- elif type(doc_to_target) == list:
- return doc_to_target
- elif callable(doc_to_target):
- return doc_to_target(doc, self.model_specific_target_kwargs) if self.model_specific_target_kwargs is not None else doc_to_target(doc)
- # Used when applying a Promptsource template
- elif hasattr(doc_to_target, "apply"):
- applied_prompt = doc_to_target.apply(doc)
- if len(applied_prompt) == 2:
- return applied_prompt[1]
- else:
- eval_logger.warning("Applied prompt returns empty string")
- return self.config.fewshot_delimiter
- else:
- raise TypeError
-
- def doc_to_visual(self, doc: dict) -> Union[int, str, list]:
- self.config.doc_to_visual
- if type(self.config.doc_to_visual) == str:
- assert self.config.doc_to_visual in self.features
- # Single image. Still return a list for consistency.
- return [doc[self.config.doc_to_visual]]
- else:
- assert callable(self.config.doc_to_visual)
- return self.config.doc_to_visual(doc)
-
- def doc_to_choice(self, doc: Any) -> List[str]:
- if self.config.doc_to_choice is None:
- eval_logger.error("doc_to_choice was called but not set in config")
- else:
- doc_to_choice = self.config.doc_to_choice
-
- if type(doc_to_choice) == str:
- if doc_to_choice in self.features:
- return doc[doc_to_choice]
- else:
- return ast.literal_eval(utils.apply_template(doc_to_choice, doc))
- elif type(doc_to_choice) == list:
- return doc_to_choice
- elif type(doc_to_choice) == dict:
- return list(doc_to_choice.values())
- elif callable(doc_to_choice):
- return doc_to_choice(doc)
- elif hasattr(doc_to_choice, "get_answer_choices_list"):
- return doc_to_choice.get_answer_choices_list(doc)
- else:
- raise TypeError
-
- def construct_requests(self, doc_id: int, ctx: str, **kwargs) -> Union[List[Instance], Instance]:
- split = kwargs.get("split")
- kwargs.pop("split")
- if self.OUTPUT_TYPE == "loglikelihood":
- arguments = (ctx, self.doc_to_target, self.doc_to_visual, doc_id, self.config.task, split)
- elif self.OUTPUT_TYPE == "multiple_choice":
- doc = self.dataset[split][doc_id]
- choices = self.doc_to_choice(doc)
- target_delimiter = self.config.target_delimiter
- if self.multiple_input:
- # If there are multiple inputs, choices are placed in the ctx
- cont = self.doc_to_target(doc)
- arguments = [(ctx, f"{target_delimiter}{cont}", self.doc_to_visual, doc_id, self.config.task, split) for ctx in choices]
- else:
- # Otherwise they are placed in the continuation
- arguments = [(ctx, f"{target_delimiter}{cont}", self.doc_to_visual, doc_id, self.config.task, split) for cont in choices]
- request_list = [
- Instance(
- request_type="loglikelihood",
- # doc=doc,
- arguments=arg,
- idx=i,
- **kwargs,
- )
- for i, arg in enumerate(arguments)
- ]
- # TODO: we should raise a warning telling users this will at most ~2x runtime.
- if "acc_mutual_info" in self._metric_fn_list.keys():
- # if we are calculating multiple choice accuracy
- # using mutual information instead of raw loglikelihood as metric, need unconditional lls.
-
- # here mutual info refers to calculating
- # log(P(choice|ctx) / P(choice)) = log(P(choice|ctx)) - log(P(choice))
- # in other words normalizing by subtracting the unconditional logprob of each choice.
- request_list.extend(
- [
- Instance(
- request_type="loglikelihood",
- # doc=doc,
- arguments=("", "{}".format(choice)),
- idx=i,
- **kwargs,
- )
- for i, choice in enumerate(choices)
- ]
- )
- return request_list
-
- elif self.OUTPUT_TYPE == "generate_until":
- arguments = (ctx, self.config.generation_kwargs, self.doc_to_visual, doc_id, self.config.task, split)
- return Instance(request_type=self.OUTPUT_TYPE, arguments=arguments, idx=0, **kwargs)
-
- # TODO: we add a full_docs interface here for some evaluations that needs to access the full datasets during process_results function. we may have better ways to handle this.
- @retry(stop=(stop_after_attempt(5) | stop_after_delay(1200)), wait=wait_fixed(2))
- def process_results(self, doc, results, full_docs=None):
- if self.OUTPUT_TYPE == "generate_until":
- results[0] = results[0].strip()
-
- kwargs = {}
- if full_docs is not None:
- kwargs["full_docs"] = full_docs
- if callable(self.config.process_results):
- return self.config.process_results(doc, results, **kwargs)
-
- result_dict = {}
- use_metric = list(self._metric_fn_list.keys())
- if self.OUTPUT_TYPE == "loglikelihood":
- results = results[0]
- ll, is_greedy = results
- return {
- **({"perplexity": ll} if "perplexity" in use_metric else {}),
- **({"acc": int(is_greedy)} if "acc" in use_metric else {}),
- }
- elif self.OUTPUT_TYPE == "multiple_choice":
- lls, is_greedy = zip(*results)
-
- # retrieve choices in List[str] form, to compute choice lengths, etc.
- choices = self.doc_to_choice(doc)
- completion_len = np.array([float(len(i)) for i in choices])
-
- if 2 * len(choices) == len(lls) and "acc_mutual_info" in self._metric_fn_list.keys():
- # then we are doing mutual info.
- # this stores the "dryrun" / unconditional answer loglikelihoods
- lls_unconditional = lls[1::2]
- assert len(lls_unconditional) == len(choices)
- # and this stores our "regular" conditional loglikelihoods
- lls = lls[::2]
-
- pred = np.argmax(lls)
- pred_norm = np.argmax(lls / completion_len)
-
- if self.multiple_input:
- gold = self.doc_to_text(doc)
- else:
- gold = self.doc_to_target(doc)
-
- gold_index_error = False
- if type(gold) is list:
- gold = [i if i < len(choices) else -100 for i in gold]
- if -100 in gold:
- gold_index_error = True
- else:
- if type(gold) is int:
- gold = gold if gold < len(choices) else -100
- elif type(gold) is str:
- gold = choices.index(gold) if gold in choices else -100
-
- if gold == -100:
- gold_index_error = True
-
- if gold_index_error:
- eval_logger.warning(f"Label index was not in within range of available choices," f"Sample:\n\n{doc}\n\n")
-
- if self.multiple_target:
- acc = 1.0 if pred in gold else 0.0
- acc_norm = 1.0 if pred_norm in gold else 0.0
- exact_match = int(any([is_greedy[i] if i != -100 else 0 for i in gold]))
- else:
- acc = 1.0 if pred == gold else 0.0
- acc_norm = 1.0 if pred_norm == gold else 0.0
- # TODO: this gets score of 0 on arc_challenge for pythia-70m. need to test that this works properly
- exact_match = int(is_greedy[gold]) if gold != -100 else 0
-
- result_dict = {
- **({"acc": acc} if "acc" in use_metric else {}),
- **({"f1": (gold, pred)} if "f1" in use_metric else {}),
- **({"mcc": (gold, pred)} if "mcc" in use_metric else {}),
- **({"acc_norm": acc_norm} if "acc_norm" in use_metric else {}),
- **({"exact_match": exact_match} if "exact_match" in use_metric else {}),
- }
-
- if "acc_mutual_info" in use_metric:
- lls_mutual_info = [ll_c - ll_u for ll_c, ll_u in zip(lls, lls_unconditional)]
- acc_mutual_info = 1.0 if np.argmax(lls_mutual_info) == gold else 0.0
- result_dict["acc_mutual_info"] = acc_mutual_info
-
- elif self.OUTPUT_TYPE == "generate_until":
- gold = self.doc_to_target(doc)
- result = results[0]
- if self.config.doc_to_choice is not None:
- # If you set doc_to_choice,
- # it assumes that doc_to_target returns a number.
- choices = self.doc_to_choice(doc)
- gold = choices[gold]
- # we expect multiple_targets to be a list.
- elif self.multiple_target:
- gold = list(gold)
- elif type(gold) != type(result):
- # cast gold to the same type as result
- gold = type(result)(gold)
-
- for metric in self._metric_fn_list.keys():
- if self.multiple_target:
- # in the case where we have multiple targets,
- # return true if any are true
- # TODO: this may break for multipLe_target, non zero-or-1 metrics
- scores = []
- if not isinstance(gold, list):
- # sometimes, a multiple_target dataset has exceptions where one doc has only one string answer
- # print(gold)
- gold = [gold]
- for gold_option in gold:
- try:
- result_score = self._metric_fn_list[metric](
- references=[gold_option],
- predictions=[result],
- **self._metric_fn_kwargs[metric],
- )
- except TypeError: # TODO: this is hacky and I don't want to do it
- result_score = self._metric_fn_list[metric]([gold_option, result])
- if isinstance(result_score, dict):
- # TODO: this handles the case where HF evaluate returns a dict.
- result_score = result_score[metric]
- scores.append(result_score)
- if any(scores):
- result_score = 1.0
- else:
- result_score = 0.0
- else:
- try:
- result_score = self._metric_fn_list[metric](
- references=[gold],
- predictions=[result],
- **self._metric_fn_kwargs[metric],
- )
- except TypeError: # needed for now in order to use a different interface between our own metrics and HF Evaluate metrics
- result_score = self._metric_fn_list[metric]([gold, result])
- if isinstance(result_score, dict):
- # TODO: this handles the case where HF evaluate returns a dict.
- result_score = result_score[metric]
- result_dict[metric] = result_score
- else:
- raise ValueError(
- f"Passed invalid output_type '{self.OUTPUT_TYPE}' ! Please use one of ",
- "'loglikelihood','generate_until' or 'multiple_choice'",
- )
-
- return result_dict
-
- def aggregation(self):
- return self._aggregation_list
-
- def higher_is_better(self):
- return self._higher_is_better
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/evaluator.py b/lmms-eval-0.2.0.post1/lmms_eval/evaluator.py
deleted file mode 100644
index 0104b01a7d8a5a129c739f3e87778fa0f84ba91b..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/evaluator.py
+++ /dev/null
@@ -1,630 +0,0 @@
-import random
-import itertools
-import json
-import collections
-import sys
-import inspect
-from tqdm import tqdm
-
-import torch
-
-import numpy as np
-from datasets import Image, Sequence
-
-import lmms_eval.api
-import lmms_eval.tasks
-import lmms_eval.models
-import lmms_eval.api.metrics
-import lmms_eval.api.registry
-
-from lmms_eval.utils import (
- positional_deprecated,
- run_task_tests,
- make_table,
- create_iterator,
- get_git_commit_hash,
- simple_parse_args_string,
-)
-
-from loguru import logger as eval_logger
-
-
-@positional_deprecated
-def simple_evaluate(
- model,
- model_args=None,
- tasks=[],
- num_fewshot=None,
- batch_size=None,
- device=None,
- limit=None,
- bootstrap_iters: int = 100000,
- check_integrity: bool = False,
- show_task_to_terminal: bool = False,
- log_samples: bool = True,
- gen_kwargs: str = None,
- cli_args=None, # Bo: put args into more functions (cost 48 Bytes per call)
- predict_only: bool = False,
-):
- """Instantiate and evaluate a model on a list of tasks.
-
- :param model: Union[str, LMM]
- Name of model or LMM object, see lmms_eval.models.get_model
- :param model_args: Optional[str]
- String arguments for each model class, see LMM.create_from_arg_string.
- Ignored if `model` argument is a LMM object.
- :param tasks: list[Union[str, Task]]
- List of task names or Task objects. Task objects will be taken to have name task.EVAL_HARNESS_NAME if defined and type(task).__name__ otherwise.
- :param num_fewshot: int
- Number of examples in few-shot context
- :param batch_size: int or str, optional
- Batch size for model
- :param device: str, optional
- PyTorch device (e.g. "cpu" or "cuda:0") for running models
- :param limit: int or float, optional
- Limit the number of examples per task (only use this for testing), If <1, limit is a percentage of the total number of examples.
- :param bootstrap_iters:
- Number of iterations for bootstrap statistics
- :param check_integrity: bool
- Whether to run the relevant part of the test suite for the tasks
- :param show_task_to_terminal: bool
- If True, write out an example document and model input for checking task integrity
- :param log_samples: bool
- If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
- :param gen_kwargs: str
- String arguments for model generation
- Ignored for all tasks with loglikelihood output_type
- :return
- Dictionary of results
- """
- random.seed(0)
- np.random.seed(1234)
- torch.manual_seed(1234) # TODO: this may affect training runs that are run with evaluation mid-run.
-
- assert tasks != [], "No tasks specified, or no tasks found. Please verify the task names."
-
- if gen_kwargs:
- gen_kwargs = simple_parse_args_string(gen_kwargs)
- eval_logger.warning(f"generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.")
- if gen_kwargs == "":
- gen_kwargs = None
-
- if model_args is None:
- model_args = ""
- lm = lmms_eval.api.registry.get_model(model).create_from_arg_string(
- model_args,
- {
- "batch_size": batch_size,
- "device": device,
- },
- )
-
- task_dict = lmms_eval.tasks.get_task_dict(tasks, model_name=model)
- for task_name in task_dict.keys():
- task_obj = task_dict[task_name]
- if type(task_obj) == tuple:
- group, task_obj = task_obj
- if task_obj is None:
- continue
- lm.task_dict[task_name] = task_obj.dataset
-
- config = task_obj._config
- if config["output_type"] == "generate_until" and gen_kwargs:
- config["generation_kwargs"].update(gen_kwargs)
-
- if predict_only:
- log_samples = True
- eval_logger.info(f"Processing {task_name} in output-only mode. Metrics will not be calculated!")
- # we have to change the class properties post-hoc. This is pretty hacky.
- task_obj.override_metric(metric_name="bypass")
-
- if num_fewshot is not None:
- if config["num_fewshot"] == 0:
- eval_logger.info(f"num_fewshot has been set to 0 for {task_name} in its config. Manual configuration will be ignored.")
- else:
- default_num_fewshot = config["num_fewshot"]
- eval_logger.warning(f"Overwriting default num_fewshot of {task_name} from {default_num_fewshot} to {num_fewshot}")
-
- task_obj._config["num_fewshot"] = num_fewshot
-
- if check_integrity:
- run_task_tests(task_list=tasks)
-
- results = evaluate(
- lm=lm,
- task_dict=task_dict,
- limit=limit,
- bootstrap_iters=bootstrap_iters,
- show_task_to_terminal=show_task_to_terminal,
- log_samples=log_samples,
- cli_args=cli_args,
- )
-
- if lm.rank == 0:
- # add info about the model and few shot config
- results["model_configs"] = {
- "model": model if isinstance(model, str) else model.model.config._name_or_path,
- "model_args": model_args,
- "batch_size": batch_size,
- "device": device,
- "limit": limit,
- "bootstrap_iters": bootstrap_iters,
- "gen_kwargs": gen_kwargs,
- }
- results["git_hash"] = get_git_commit_hash()
- return results
- else:
- return None
-
-
-decontaminate_suffix = "_decontaminate"
-
-
-@positional_deprecated
-def evaluate(
- lm,
- task_dict,
- limit=None,
- bootstrap_iters: int = 100000,
- show_task_to_terminal: bool = False,
- log_samples: bool = True,
- cli_args=None,
-):
- """Instantiate and evaluate a model on a list of tasks.
-
- :param lm: obj
- Language Model
- :param task_dict: dict[str, Task]
- Dictionary of tasks. Tasks will be taken to have name type(task).config.task .
- :param limit: int, optional
- Limit the number of examples per task (only use this for testing)
- :param bootstrap_iters:
- Number of iterations for bootstrap statistics
- :param show_task_to_terminal: bool
- If True, write out an example document and model input for checking task integrity
- :param log_samples: bool
- If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
- :return
- Dictionary of results
- """
-
- # stores the final result for each task, for each metric/filter pair.
- results = collections.defaultdict(dict)
- # Tracks each task's version.
- versions = collections.defaultdict(dict)
- # Tracks the YAML configs of all chosen tasks.
- configs = collections.defaultdict(dict)
- # logs info about each document evaluated.
- samples = collections.defaultdict(list)
- # tracks all Instances/requests a model must generate output on.
- requests = collections.defaultdict(list)
- # Aggregated task scores presented with groups
- results_agg = collections.defaultdict(dict)
- # Aggregated groups scores only
- groups_agg = collections.defaultdict(dict)
- # stores the amount to pad out reqs per req. type so that
- # number of fwd passes per distributed rank is equal
- padding_requests = collections.defaultdict(int)
- # store the hierarchy to do proper ordering
- task_hierarchy = collections.defaultdict(list)
- # store the ordering of tasks and groups
- task_order = collections.defaultdict(int)
- task_group_alias = collections.defaultdict(dict)
- # store num-fewshot value per task
- num_fewshot = collections.defaultdict(int)
-
- # get lists of each type of request
- for task_name, task in task_dict.items():
- if type(task) == tuple:
- group_name, task = task
- task_hierarchy[group_name].append(task_name)
- versions[group_name] = "N/A"
-
- else:
- group_name = None
- task_hierarchy[task_name] = []
-
- if task is None:
- continue
-
- versions[task_name] = task.VERSION
- configs[task_name] = dict(task.dump_config())
-
- if "num_fewshot" in configs[task_name]:
- n_shot = configs[task_name]["num_fewshot"]
- else:
- n_shot = 0
- num_fewshot[task_name] = n_shot
-
- if "task_alias" in configs[task_name]:
- task_group_alias[task_name] = configs[task_name]["task_alias"]
-
- if ("group_alias" in configs[task_name]) and (group_name not in task_group_alias) and (group_name is not None):
- task_group_alias[group_name] = configs[task_name]["group_alias"]
-
- if limit is not None:
- if task.has_test_docs():
- task_docs = task.test_docs()
- elif task.has_validation_docs():
- task_docs = task.validation_docs()
- else:
- raise RuntimeError("Task has neither test_docs nor validation_docs")
- limit = int(len(task_docs) * limit) if limit < 1.0 else int(limit)
-
- task.build_all_requests(limit=limit, rank=lm.rank, world_size=lm.world_size)
-
- eval_logger.debug(f"Task: {task_name}; number of requests on rank {lm.rank}: {len(task.instances)}")
-
- if show_task_to_terminal:
- for inst in task.instances:
- # print the prompt for the first few documents
- if inst.doc_id < 1:
- eval_logger.info(
- f"Task: {task_name}; document {inst.doc_id}; context prompt (starting on next line):\
-\n{inst.args[0]}\n(end of prompt on previous line)\ntarget string or answer choice index (starting on next line):\n{task.doc_to_target(inst.doc)}\n(end of target on previous line)"
- )
- eval_logger.info(f"Request: {str(inst)}")
-
- # aggregate Instances by LMM method requested to get output.
- for instance in task.instances:
- reqtype = instance.request_type
- requests[reqtype].append(instance)
-
- if lm.world_size > 1:
- instances_rnk = torch.tensor(len(task._instances), device=lm.device)
- gathered_item = lm.accelerator.gather(instances_rnk).cpu().detach().numpy().tolist()
-
- # compute number of pseudobatches to pad with (FSDP/DDP require even batches among ranks)
- numpad = max(gathered_item) - gathered_item[lm.rank]
- padding_requests[task.OUTPUT_TYPE] += numpad
-
- ### Run LMM on inputs, get all outputs ###
- # execute each type of request
- for reqtype, reqs in requests.items():
- eval_logger.info("Running {} requests".format(reqtype))
- # create `K` copies of each request `req` based off `K = req.repeats`
- cloned_reqs = []
- for req in reqs:
- cloned_reqs.extend([req] * req.repeats)
-
- if (lm.world_size > 1) and (padding_requests[reqtype] > 0):
- for _ in range(padding_requests[reqtype]):
- cloned_reqs.extend([req] * req.repeats)
-
- # run requests through model
- resps = getattr(lm, reqtype)(cloned_reqs) # Choiszt run generate until
-
- # put responses from model into a list of length K for each request.
- for x, req in zip(resps, cloned_reqs):
- req.resps.append(x)
-
- if lm.world_size > 1:
- lm.accelerator.wait_for_everyone()
-
- ### Postprocess outputs ###
- # TODO: del model here, maybe (idea: allow user to specify device of e.g. reward model separately)
- for task_name, task in task_dict.items():
- if type(task) == tuple:
- group, task = task
- if task is None:
- continue
- task.apply_filters()
-
- ### Collect values of metrics on all datapoints ###
- vals = collections.defaultdict(list)
-
- # unpack results and sort back in order and return control to Task
- for task_name, task in task_dict.items():
- if type(task) == tuple:
- group, task = task
- if task is None:
- continue
- # TODO: make it possible to use a different metric per filter
- # iterate over different filters used
- for key in task.instances[0].filtered_resps.keys():
- # hack: remove image columns to speed avoid loading images and speed up postprocessing
- # reason: doc_iterator will actually load image if it's in the doc.
- docs = task.test_docs() if task.has_test_docs() else task.validation_docs()
- if "d170" not in task_name and "dc100" not in task_name and "dc200" not in task_name and "llava_wilder" not in task_name and "livebench" not in task_name:
- remove_cols = []
- features = docs.features
- # If it is an Image instance or a Sequence of Image instance. Remove it
- for feature in features:
- if isinstance(features[feature], Image):
- remove_cols.append(feature)
- elif isinstance(features[feature], Sequence) and isinstance(features[feature].feature, Image):
- remove_cols.append(feature)
- if remove_cols:
- docs = docs.remove_columns(remove_cols)
-
- ####################### Processing with Full Docs Mode #######################
- if task_name in ["videochatgpt_consistency"]:
- full_docs = True
- else:
- full_docs = False
-
- doc_iterator = itertools.islice(enumerate(docs), lm.rank, limit, lm.world_size)
- # Instead of converting the iterator to a list, use `itertools.tee` to create a parallel iterator for counting
- # doc_iterator, doc_iterator_for_counting = itertools.tee(doc_iterator)
- # Don't use above one, this would crash if doc_iterator_for_counting contains too many objects and very slow
- doc_iterator_for_counting = itertools.islice(range(len(task.test_docs())), lm.rank, limit, lm.world_size) if task.has_test_docs() else itertools.islice(range(len(task.validation_docs())), lm.rank, limit, lm.world_size)
- total_docs = sum(1 for _ in doc_iterator_for_counting)
- pbar = tqdm(total=total_docs, desc=f"Postprocessing", disable=(lm.rank != 0))
- for doc_id, doc in doc_iterator:
- # subset instances to only this document id ; sort by idx
- requests = list(filter(lambda x: x.doc_id == doc_id, task.instances))
- requests.sort(key=lambda x: x.idx)
- if full_docs:
- metrics = task.process_results(doc, [req.filtered_resps[key] for req in requests], full_docs=docs)
- else:
- metrics = task.process_results(doc, [req.filtered_resps[key] for req in requests])
- if log_samples:
- target = task.doc_to_target(doc)
- example = {
- "doc_id": doc_id,
- "target": target,
- "doc": doc,
- "arguments": [tuple(a for a in req.args if isinstance(a, (int, str))) for req in requests], # do not include image
- "resps": [req.resps for req in requests],
- "filtered_resps": [req.filtered_resps[key] for req in requests],
- }
- example.update(metrics)
- samples[task_name].append(example)
- for metric, value in metrics.items():
- vals[(task_name, key, metric)].append(value)
- pbar.update(1)
-
- pbar.close()
-
- if lm.world_size > 1:
- # if multigpu, then gather data across all ranks
- # first gather logged samples across all ranks
- for task_name, task_samples in list(samples.items()):
- full_samples = [None] * lm.world_size
- torch.distributed.all_gather_object(full_samples, task_samples)
- samples[task_name] = list(itertools.chain.from_iterable(full_samples))
- # then collect metrics across all ranks
- vals_torch = collections.defaultdict(list)
- for (task_name, key, metric), items in vals.items():
- numitem = 0
- if type(items[0]) == tuple:
- numitem = len(items[0])
-
- if isinstance(items[0], (str, list, dict)):
- # handle the string case
- gathered_items = [None] * lm.accelerator.num_processes
- torch.distributed.all_gather_object(gathered_items, items)
-
- gathered_item = list(itertools.chain.from_iterable(gathered_items))
- else:
- # distributed gather requires all ranks to have same dimensions
- # so we pad out with float32 min value
- pad_value = torch.finfo(torch.float32).min
- metrics_tensor = torch.tensor(items, device=lm.device)
-
- original_dtype = metrics_tensor.dtype # store original dtype
- torch_device_tensor = lm.accelerator.pad_across_processes(metrics_tensor.to(torch.float32), pad_index=pad_value)
- gathered_item = lm.accelerator.gather(torch_device_tensor)
-
- if numitem > 0:
- gathered_filtered = gathered_item[gathered_item[:, 0] != pad_value]
- else:
- gathered_filtered = gathered_item[gathered_item != pad_value]
-
- gathered_item = gathered_filtered.to(original_dtype).cpu().detach().numpy().tolist()
- # reconvert if we were passed a tuple of values
- if numitem > 0:
- gathered_item = [tuple(g) for g in gathered_item]
-
- if lm.rank == 0:
- vals_torch[(task_name, key, metric)] = gathered_item
-
- vals = vals_torch
- # Ensure all ranks wait for rank 0 to finish aggregation
- torch.distributed.barrier()
-
- if lm.rank == 0:
- ### Get task ordering for correct sample-wide aggregation
- group_to_task = {}
- for group in task_hierarchy.keys():
- if group not in task_order:
- task_order[group] = 0
-
- if len(task_hierarchy[group]) > 0:
- group_to_task[group] = task_hierarchy[group].copy()
-
- for task in task_hierarchy[group]:
- if task in task_order:
- task_order[task] += 1
- else:
- task_order[task] = 1 + task_order[group]
-
- if task in task_hierarchy:
- group_to_task[group].remove(task)
- group_to_task[group].extend(task_hierarchy[task])
-
- task_to_group = {}
- for group in group_to_task:
- for task in group_to_task[group]:
- if task in task_to_group:
- task_to_group[task].append(group)
- else:
- task_to_group[task] = [group]
-
- ### Aggregate results over all datapoints ###
- # aggregate results ; run bootstrap CIs
- for (task_name, key, metric), items in vals.items():
- task = task_dict[task_name]
- metric_key = metric + "," + key
-
- if type(task) == tuple:
- group_name, task = task
- else:
- group_name = None
-
- if metric not in task.aggregation():
- continue
-
- agg_fn = task.aggregation()[metric]
-
- # Bo: for models that need to know the args to save to correct path
- if inspect.getfullargspec(agg_fn).args == ["results", "args"]:
- results[task_name][metric_key] = agg_fn(items, cli_args)
- else:
- # Bo: for models only need agg items
- results[task_name][metric_key] = agg_fn(items)
-
- results[task_name]["samples"] = len(items)
-
- # hotfix: bleu, chrf, ter seem to be really expensive to bootstrap
- # so we run them less iterations. still looking for a cleaner way to do this
- if bootstrap_iters > 0:
- stderr = lmms_eval.api.metrics.stderr_for_metric(
- metric=task.aggregation()[metric],
- bootstrap_iters=min(bootstrap_iters, 100) if metric in ["bleu", "chrf", "ter"] else bootstrap_iters,
- )
-
- if stderr is not None and len(items) > 1:
- results[task_name][metric + "_stderr" + "," + key] = stderr(items)
- else:
- results[task_name][metric + "_stderr" + "," + key] = "N/A"
-
- if bool(results):
- for group, task_list in reversed(task_hierarchy.items()):
- if task_list == []:
- total_size = results[group]["samples"]
- else:
- total_size = 0
-
- for task in task_list:
- metrics = results[task]
-
- current_size = metrics.pop("samples")
- # TODO: There should be a way for users
- # to toggle between weighted and
- # unweighted averaging
- # For unweighted averaging, use:
- # current_size = 1
-
- all_stderr = []
- for metric in [key for key in metrics.keys() if "_stderr" not in key]:
- stderr = "_stderr,".join(metric.split(","))
- stderr_score = results[task][stderr]
- var_score = stderr_score**2 if stderr_score != "N/A" else 0
- metric_score = results[task][metric]
-
- all_stderr.append(stderr)
-
- if metric_score is None:
- results[group][metric] = None
- results[group][stderr] = 0
- continue
-
- if metric in results[group]:
- if isinstance(results[group][metric], str) == False:
- results[group][metric] = (results[group][metric] * total_size + metric_score * current_size) / (total_size + current_size)
- # $$s_z^2 = \frac{(n-1) s_x^2 + (m-1) s_y^2}{n+m-1} + \frac{nm(\bar x - \bar y)^2}{(n+m)(n+m-1)}.$$
- results[group][stderr] = ((total_size - 1) * results[group][stderr] + (current_size - 1) * var_score) / (total_size + current_size - 1) + total_size * current_size / (
- (total_size + current_size) * (total_size + current_size - 1)
- ) * (results[group][metric] - metric_score) ** 2
- else:
- # accuracy = re.search(r'acc: ([\d.]+)%', results[group][metric]).group(1)
- # score = re.search(r'score: ([\d.]+)', results[group][metric]).group(1)
- # group_accuracy = float(accuracy)
- # group_score = float(score)
- # group_accuracy = (group_accuracy * total_size + metric_score * current_size) / total_size
- # group_score = (group_score * total_size + metric_score * current_size) / total_size
- # results[group][metric] = "Acc: " + str(group_accuracy) + " Score: " + str(group_score)
- results[group][metric] = "group_results"
- results[group][stderr] = 0
- else:
- results[group][metric] = metric_score
- results[group][stderr] = var_score
-
- total_size += current_size
-
- for stderr in all_stderr:
- results[group][stderr] = np.sqrt(results[group][stderr])
-
- results[group]["samples"] = total_size
-
- def print_tasks(task_hierarchy, task_order, task_version, task_group_alias):
- results_agg = collections.defaultdict(dict)
- groups_agg = collections.defaultdict(dict)
- for group_name, task_list in task_hierarchy.items():
- order = task_order[group_name]
- results_agg[group_name] = results[group_name].copy()
- results_agg[group_name]["tab"] = order
-
- if (order < max(task_order.values())) and (len(task_list) > 0):
- groups_agg[group_name] = results[group_name].copy()
- groups_agg[group_name]["tab"] = order
-
- if task_list != []:
- for task in sorted(task_list):
- if task in task_hierarchy:
- _task_hierarchy = {task: task_hierarchy[task]}
- else:
- _task_hierarchy = {task: []}
-
- _results_agg, _groups_agg, task_version = print_tasks(_task_hierarchy, task_order, task_version, task_group_alias)
-
- results_agg = {**results_agg, **_results_agg}
- groups_agg = {**groups_agg, **_groups_agg}
-
- return results_agg, groups_agg, task_version
-
- results_agg, groups_agg, versions = print_tasks(task_hierarchy, task_order, versions, task_group_alias)
-
- for task in results_agg:
- task_results = results_agg[task]
-
- if "samples" in task_results:
- task_results.pop("samples")
-
- tab_string = ""
- if "tab" in task_results:
- tab = task_results.pop("tab")
- tab_string = " " * tab + "- " if tab > 0 else ""
-
- if task in task_group_alias:
- task_alias = task_group_alias[task]
- results_agg[task]["alias"] = tab_string + task_alias
- else:
- results_agg[task]["alias"] = tab_string + task
-
- for group in groups_agg:
- group_results = groups_agg[group]
-
- if "samples" in group_results:
- group_results.pop("samples")
-
- tab_string = ""
- if "tab" in group_results:
- tab = group_results.pop("tab")
- tab_string = " " * tab + "- " if tab > 0 else ""
-
- if group in task_group_alias:
- group_alias = task_group_alias[group]
- groups_agg[group]["alias"] = tab_string + group_alias
- else:
- groups_agg[group]["alias"] = tab_string + group
-
- for group_name, task_list in task_hierarchy.items():
- if task_list != []:
- num_fewshot[group_name] = num_fewshot[task_list[0]]
-
- results_dict = {
- "results": dict(results_agg.items()),
- **({"groups": dict(groups_agg.items())} if bool(groups_agg) else {}),
- "configs": dict(sorted(configs.items())),
- "versions": dict(sorted(versions.items())),
- "n-shot": dict(sorted(num_fewshot.items())),
- }
- if log_samples:
- results_dict["samples"] = dict(samples)
-
- return results_dict
-
- else:
- return None
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/filters/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/filters/__init__.py
deleted file mode 100644
index 38ab7d8a5f6234e11a06864b26a93aa7c588e6a8..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/filters/__init__.py
+++ /dev/null
@@ -1,45 +0,0 @@
-from lmms_eval.api.filter import FilterEnsemble, Filter
-from . import selection
-from . import extraction
-from . import transformation
-
-
-FILTER_REGISTRY = {
- "take_first": selection.TakeFirstFilter,
- "regex": extraction.RegexFilter,
- "majority_vote": selection.MajorityVoteFilter,
- "take_first_k": selection.TakeKFilter,
- "remove_whitespace": extraction.WhitespaceFilter,
- "lowercase": transformation.LowercaseFilter,
- "uppercase": transformation.UppercaseFilter,
- "map": transformation.MapFilter,
- "multi_choice_regex": extraction.MultiChoiceRegexFilter,
- # TODO: implement this filter. either it should take in an arbitrary "scoring"/reward function
- # that takes an input and returns a scalar and then should select the max reward,
- # or should implement different filters for different ways of handling a reward model's inference.
- # "arg_max": selection.ArgMaxFilter,
-}
-
-
-def get_filter(filter_name):
- if filter_name in FILTER_REGISTRY:
- return FILTER_REGISTRY[filter_name]
- else:
- return filter_name
-
-
-def build_filter_ensemble(filter_name, components):
- """
- Create a filtering pipeline.
- """
- filters = []
- for function, kwargs in components:
- if kwargs is None:
- f = get_filter(function)()
- else:
- # create a filter given its name in the registry
- f = get_filter(function)(**kwargs) # TODO: pass kwargs to filters properly
- # add the filter as a pipeline step
- filters.append(f)
-
- return FilterEnsemble(name=filter_name, filters=filters)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/filters/decontamination.py b/lmms-eval-0.2.0.post1/lmms_eval/filters/decontamination.py
deleted file mode 100644
index d2e1b4504ccbfcf792e3e061de333a24b8c75940..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/filters/decontamination.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from lmms_eval.api.filter import Filter
-
-
-class DecontaminationFilter(Filter):
- """
- A filter which evaluates
- """
-
- name = "track_decontamination"
-
- def __init__(self, path) -> None:
- """
-
- TODO: make sure only ever run one time on the train set (should this be cached as a class var? keyed by value for "path").
- should further cache result on a given (task_name, doc_id)
- """
- self._decontam_results = None
-
- def apply(self, resps, docs) -> None:
- """
- Return {"no_contamination", "only_contamination"} keys for the 2 different subsets
- """
- pass
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/filters/extraction.py b/lmms-eval-0.2.0.post1/lmms_eval/filters/extraction.py
deleted file mode 100644
index f3045673b30a822f954f1fc9b4fbb927944500b4..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/filters/extraction.py
+++ /dev/null
@@ -1,278 +0,0 @@
-import re
-import sys
-import unicodedata
-from lmms_eval.api.filter import Filter
-
-
-class WhitespaceFilter(Filter):
- """ """
-
- def __init__(self) -> None:
- pass
-
- def apply(self, resps, docs):
- def filter_set(inst):
- filtered_resp = []
- for resp in inst:
- if resp.startswith(" "):
- resp = resp[1:]
-
- filtered_resp.append(resp)
-
- return filtered_resp
-
- filtered_resps = [filter_set(resp) for resp in resps]
-
- return filtered_resps
-
-
-class RegexFilter(Filter):
- """ """
-
- def __init__(
- self,
- regex_pattern: str = r"#### (\-?[0-9\.\,]+)",
- group_select=0,
- fallback: str = "[invalid]",
- ) -> None:
- """
- pass a string `regex` to run `re.compile(r"regex")` on.
- `fallback` defines the output returned if no matches for the regex are located.
- """
- self.regex_pattern = regex_pattern
- self.regex = re.compile(regex_pattern)
- self.group_select = group_select
- self.fallback = fallback
-
- def apply(self, resps, docs):
- # here, we assume we have a list, in which each element is
- # a list of model responses for some particular input/target pair.
- # so we process each of these (same input/target response sets)
- # independently (and keep them a list.)
- def filter_set(inst):
- filtered = []
- for resp in inst:
- match = self.regex.findall(resp)
- if match:
- match = match[self.group_select]
- if isinstance(match, tuple):
- match = [m for m in match if m][0]
- match = match.strip()
- else:
- match = self.fallback
- filtered.append(match)
- return filtered
-
- # print(resps)
- filtered_resps = list(map(lambda x: filter_set(x), resps))
- # print(filtered_resps)
-
- return filtered_resps
-
-
-class MultiChoiceRegexFilter(RegexFilter):
- """
- A filter used to extract a model's answer on multiple choice questions with
- letter answers. assumes each document has a "choices" field
- containing the list of answer choices and that the answer label symbols
- are of the form (A), (B), (C), ... or A, B, C.
- """
-
- def __init__(
- self,
- regex_pattern: str = r"#### (\-?[0-9\.\,]+)",
- group_select=0,
- fallback: str = "[invalid]",
- ignore_case=False,
- ignore_punctuation=False,
- regexes_to_ignore=None,
- ) -> None:
- """
- regex_pattern: The basic regex pattern to use. If fails to match, we will use the customized match procedure
- - step 1 : We parse the choices between ([A-Z])s then try to find these choices in the response.
- - step 2 : We parse the choice with regex :[\s]*([A-?]), where ? varies by number of choices.
- group_select: Selects the (group_select)th match from the findall result.
- ignore_case: Ignores the case during step 1 matching
- ignore_punctuation: Remove the punctuation during step 1 matching
- regexes_to_ignore: Remove these regexes during step 1 matching
- """
- super().__init__(regex_pattern, group_select, fallback)
- self.ignore_case = ignore_case
- self.ignore_punctuation = ignore_punctuation
- self.regexes_to_ignore = regexes_to_ignore
-
- def apply(self, resps, docs):
- # here, we assume we have a list, in which each element is
- # a list of model responses for some particular input/target pair.
- # so we process each of these (same input/target response sets)
- # independently (and keep them a list.)
-
- def find_match(regex, resp, convert_dict={}):
- match = regex.findall(resp)
- if match:
- match = match[self.group_select]
- if isinstance(match, tuple):
- match = [m for m in match if m][0]
- match = match.strip()
- if match and match in convert_dict:
- match = convert_dict[match]
- return match
-
- punct_tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith("P"))
-
- def filter_ignores(st):
- if self.regexes_to_ignore is not None:
- for s in self.regexes_to_ignore:
- st = re.sub(s, "", st)
-
- if self.ignore_case:
- st = st.lower()
-
- if self.ignore_punctuation:
- # https://stackoverflow.com/a/266162
- st = st.translate(punct_tbl)
- return st
-
- filtered_resps = []
-
- for r, doc in zip(resps, docs):
- fallback_regexes = []
- choice_to_alpha = {}
- next_alpha = "A"
-
- without_paren_fallback_regexes = []
- without_paren_to_target = {}
-
- choices = doc["choices"]
- for c in choices:
- m = filter_ignores(c.strip())
- fallback_regexes.append(f"{re.escape(m)}")
- choice_to_alpha[m] = f"({next_alpha})"
-
- without_paren_fallback_regexes.append(next_alpha)
- without_paren_to_target[next_alpha] = f"({next_alpha})"
-
- next_alpha = chr(ord(next_alpha) + 1)
- fallback_regex = re.compile("|".join(fallback_regexes))
- without_paren_fallback_regex = "|".join(without_paren_fallback_regexes)
- without_paren_fallback_regex = re.compile(f":[\s]*({without_paren_fallback_regex})")
-
- filtered = []
- for resp in r:
- match = find_match(self.regex, resp)
- if not match:
- match = find_match(fallback_regex, filter_ignores(resp), choice_to_alpha)
- if not match:
- match = find_match(without_paren_fallback_regex, resp, without_paren_to_target)
- if not match:
- match = self.fallback
- filtered.append(match)
- filtered_resps.append(filtered)
-
- return filtered_resps
-
-
-class ExtendedRegexFilter(RegexFilter):
- punct_tbl = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith("P"))
-
- def __init__(
- self,
- regex_pattern: str = r"#### (\-?[0-9\.\,]+)",
- group_select=0,
- fallback: str = "[invalid]",
- ignore_case=False,
- ignore_punctuation=False,
- regexes_to_ignore=None,
- ) -> None:
- super().__init__(regex_pattern, group_select, fallback)
- self.ignore_case = ignore_case
- self.ignore_punctuation = ignore_punctuation
- self.regexes_to_ignore = regexes_to_ignore
-
- def filter_ignores(self, st):
- if self.regexes_to_ignore is not None:
- for s in self.regexes_to_ignore:
- st = re.sub(s, "", st)
-
- if self.ignore_case:
- st = st.lower()
-
- if self.ignore_punctuation:
- # https://stackoverflow.com/a/266162
- st = st.translate(self.punct_tbl)
- return st
-
- def find_match(self, regex, resp, convert_dict={}):
- match = regex.findall(resp)
- if match:
- match = match[self.group_select]
- if isinstance(match, tuple):
- match = [m for m in match if m][0]
- match = match.strip()
- if match and match in convert_dict:
- match = convert_dict[match]
- return match
-
-
-# Designed for the AI2D/RealworldQA dataset
-class SimpleMultiChoiceRegexFilter(ExtendedRegexFilter):
- def __init__(self, *args, **kwargs):
- """
- regex_pattern: The basic regex pattern to use. If fails to match, we will use the customized match procedure
- - step 1 : We parse the choices between ([A-Z])s then try to find these choices in the response.
- - step 2 : We parse the choice with regex :[\s]*([A-?]), where ? varies by number of choices.
- group_select: Selects the (group_select)th match from the findall result.
- ignore_case: Ignores the case during step 1 matching
- ignore_punctuation: Remove the punctuation during step 1 matching
- regexes_to_ignore: Remove these regexes during step 1 matching
- """
- super().__init__(*args, **kwargs)
-
- def apply(self, resps, docs):
- # here, we assume we have a list, in which each element is
- # a list of model responses for some particular input/target pair.
- # so we process each of these (same input/target response sets)
- # independently (and keep them a list.)
-
- filtered_resps = []
-
- for r, doc in zip(resps, docs):
- fallback_regexes = []
- choice_to_alpha = {}
- next_alpha = "A"
-
- without_paren_fallback_regexes = []
- without_paren_to_target = {}
-
- # Regex to extract multiple choice options from the question
- multiple_choices_regex = re.compile(r"\b([A-Z])\.\s+([^\n]*)")
- matches = multiple_choices_regex.findall(doc["question"])
-
- # Build regex patterns and mappings for each choice
- for m in matches:
- choice_text = m[1].strip()
- fallback_regexes.append(f"{re.escape(choice_text)}")
- choice_to_alpha[choice_text] = next_alpha
-
- next_alpha = chr(ord(next_alpha) + 1)
-
- # Compile regex to match any of the extracted choices
- fallback_regex = re.compile("|".join(fallback_regexes))
-
- # Process each response
- filtered = []
- for resp in r:
- # Remove any punctuation and extra spaces
- cleaned_resp = re.sub(r"[^\w\s]", "", resp).strip()
- # Try to match cleaned response with the choice text
- match = fallback_regex.search(cleaned_resp)
- if match and match.group() in choice_to_alpha:
- # Map the matched choice text back to its corresponding letter
- filtered.append(choice_to_alpha[match.group()])
- else:
- # If no match, return the cleaned response
- filtered.append(cleaned_resp)
-
- filtered_resps.append(filtered[0])
-
- return filtered_resps
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/filters/selection.py b/lmms-eval-0.2.0.post1/lmms_eval/filters/selection.py
deleted file mode 100644
index acbfb828d06d685e80fb2e426f7c91705026b2f4..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/filters/selection.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from collections import Counter
-
-from lmms_eval.api.filter import Filter
-
-
-class TakeFirstFilter(Filter):
- def __init__(self) -> None:
- """
- Can define custom behavior here, if an individual instantiation of a Filter class should have state.
- """
-
- def apply(self, resps, docs):
- """
- Assuming each entry of `resps` is a list of model responses, we discard all but the first response.
- """
- return map(lambda r: r[0], resps)
-
-
-class TakeKFilter(Filter):
- def __init__(self, *args, **kwargs) -> None:
- self.k = kwargs.pop("k")
-
- super().__init__(*args, **kwargs)
-
- def apply(self, resps, docs):
- # check we have at least k responses per doc, else we can't take the first k
- assert len(resps[0]) >= self.k, f"Need at least {self.k} responses per doc to take first {self.k}, but got {len(resps[0])} only! Please increase TaskConfig.repeats ."
- return map(lambda r: r[: self.k], resps)
-
-
-class MajorityVoteFilter(Filter):
- def __init__(self) -> None:
- """
- Can define custom behavior here, if an individual instantiation of a Filter class should have state.
- """
-
- def apply(self, resps, docs):
- """
- Each entry of `resps` is a list of model responses.
- We select the response that occurs most frequently in each entry of `resps`.
- """
-
- def select_majority(resp):
- counts = Counter(resp)
- vote = counts.most_common(1)[0][0]
- return vote
-
- return map(lambda r: [select_majority(r)], resps)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/filters/transformation.py b/lmms-eval-0.2.0.post1/lmms_eval/filters/transformation.py
deleted file mode 100644
index 9842115f94a6aaaa95667d27aa6ab3da2dad3bf9..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/filters/transformation.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from lmms_eval.api.filter import Filter
-
-
-class LowercaseFilter(Filter):
- def __init__(self) -> None:
- pass
-
- def apply(self, resps, docs):
- def filter_set(inst):
- return [resp.lower() for resp in inst]
-
- return [filter_set(resp) for resp in resps]
-
-
-class UppercaseFilter(Filter):
- def __init__(self) -> None:
- pass
-
- def apply(self, resps, docs):
- def filter_set(inst):
- return [resp.upper() for resp in inst]
-
- return [filter_set(resp) for resp in resps]
-
-
-class MapFilter(Filter):
- def __init__(self, mapping_dict: dict = {}, default_value=None) -> None:
- """
- Initializes the MapFilter with a given mapping dictionary and default value.
-
- Args:
- - mapping_dict (dict): A dictionary containing the key-value mappings.
- Default is an empty dictionary.
- - default_value (Any): The value to be returned when a key is not found in the mapping_dict.
- Default is None.
-
- Example:
- mapper = MapFilter({'A': 1, 'B': 2}, default_value=0)
- """
- assert isinstance(mapping_dict, dict), "Provided mapping_dict is not a dictionary"
- self.mapping_dict = mapping_dict
- self.default_value = default_value
-
- def apply(self, resps, docs):
- def filter_set(inst):
- return [self.mapping_dict.get(resp, self.default_value) for resp in inst]
-
- return [filter_set(resp) for resp in resps]
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/logging_utils.py b/lmms-eval-0.2.0.post1/lmms_eval/logging_utils.py
deleted file mode 100644
index 4d7e09109d2a1748b4bba179a2f68c7956005acc..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/logging_utils.py
+++ /dev/null
@@ -1,367 +0,0 @@
-# Code mostly from: https://github.com/EleutherAI/lm-evaluation-harness/pull/1339, credit to: https://github.com/ayulockin
-import copy
-
-import re
-import os
-import json
-import glob
-import pandas as pd
-import numpy as np
-from datetime import datetime
-from typing import Any, Dict, List, Literal, Tuple, Union
-from packaging.version import Version
-from lmms_eval import utils
-import tenacity
-from loguru import logger
-
-try:
- import wandb
-
- assert Version(wandb.__version__) >= Version("0.13.6")
- if Version(wandb.__version__) < Version("0.13.6"):
- wandb.require("report-editing:v0")
-except Exception as e:
- logger.warning("To use the wandb reporting functionality please install wandb>=0.13.6.\n" "To install the latest version of wandb run `pip install wandb --upgrade`\n" f"{e}")
-
-
-def remove_none_pattern(input_string):
- # Define the pattern to match ',none' at the end of the string
- pattern = re.compile(r",none$")
-
- # Use sub() to replace ',none' with an empty string
- result = re.sub(pattern, "", input_string)
-
- # check if the input_string changed
- removed = result != input_string
-
- return result, removed
-
-
-def _handle_non_serializable(o: Any) -> Union[int, str, list]:
- """Handle non-serializable objects by converting them to serializable types.
-
- Args:
- o (Any): The object to be handled.
-
- Returns:
- Union[int, str, list]: The converted object. If the object is of type np.int64 or np.int32,
- it will be converted to int. If the object is of type set, it will be converted
- to a list. Otherwise, it will be converted to str.
- """
- if isinstance(o, np.int64) or isinstance(o, np.int32):
- return int(o)
- elif isinstance(o, set):
- return list(o)
- else:
- return str(o)
-
-
-def get_wandb_printer() -> Literal["Printer"]:
- """Returns a wandb printer instance for pretty stdout."""
- from wandb.sdk.lib.printer import get_printer
- from wandb.sdk.wandb_settings import Settings
-
- printer = get_printer(Settings()._jupyter)
- return printer
-
-
-# class WandbLogger:
-class WandbLogger:
- def __init__(self, args):
- self.wandb_args = utils.simple_parse_args_string(args.wandb_args)
- self.args = args
- self.all_args_dict = vars(args)
- self.printer = get_wandb_printer()
- try:
- self.init_run()
- except Exception as e:
- logger.warning(f"Failed to initialize W&B run: {e}")
- os.environ["WANDB_MODE"] = "offline"
- self.init_run()
-
- def finish(self):
- self.run.finish()
-
- @tenacity.retry(wait=tenacity.wait_fixed(5), stop=tenacity.stop_after_attempt(5))
- def init_run(self):
- if "name" not in self.wandb_args:
- if "config" in self.all_args_dict and self.all_args_dict["config"] != "":
- self.wandb_args["name"] = self.all_args_dict["config"].split("/")[-1].replace(".yaml", "") + "/" + self.args.log_samples_suffix
- else:
- task_names = self.args.tasks.replace(",", "/")
- self.wandb_args["name"] = f"{self.args.model}/<{task_names}>/{self.args.log_samples_suffix}"
- if self.args.num_fewshot:
- self.wandb_args["name"] += f"_{self.args.num_fewshot}shot"
- if "project" not in self.wandb_args:
- self.wandb_args["project"] = "lmms-eval"
- # initialize a W&B run
- self.run = wandb.init(**self.wandb_args)
-
- def post_init(self, results: Dict[str, Any]) -> None:
- self.results: Dict[str, Any] = copy.deepcopy(results)
- self.task_names: List[str] = list(results.get("results", {}).keys())
- self.group_names: List[str] = list(results.get("groups", {}).keys())
-
- def _get_config(self) -> Dict[str, Any]:
- """Get configuration parameters."""
- self.task_configs = self.results.get("configs", {})
- cli_configs = self.results.get("config", {})
- configs = {
- "task_configs": self.task_configs,
- "cli_configs": cli_configs,
- }
-
- return configs
-
- def _sanitize_results_dict(self) -> Tuple[Dict[str, str], Dict[str, Any]]:
- """Sanitize the results dictionary."""
- _results = copy.deepcopy(self.results.get("results", dict()))
- _results["model_configs"] = self.results.get("model_configs", dict())
-
- # Remove None from the metric string name
- tmp_results = copy.deepcopy(_results)
- for task_name in self.task_names:
- task_result = tmp_results.get(task_name, dict())
- for metric_name, metric_value in task_result.items():
- _metric_name, removed = remove_none_pattern(metric_name)
- if removed:
- _results[task_name][_metric_name] = metric_value
- _results[task_name].pop(metric_name)
-
- # remove string valued keys from the results dict
- wandb_summary = {}
- for task in self.task_names:
- task_result = _results.get(task, dict())
- for metric_name, metric_value in task_result.items():
- if isinstance(metric_value, str):
- wandb_summary[f"{task}/{metric_name}"] = metric_value
-
- wandb_summary["model_configs"] = self.results.get("model_configs", dict())
- for summary_metric, summary_value in wandb_summary.items():
- if summary_metric != "model_configs":
- _task, _summary_metric = summary_metric.split("/")
- _results[_task].pop(_summary_metric)
-
- tmp_results = copy.deepcopy(_results)
- for task_name, task_results in tmp_results.items():
- if task_name != "model_configs":
- for metric_name, metric_value in task_results.items():
- _results[f"{task_name}/{metric_name}"] = metric_value
- _results[task_name].pop(metric_name)
- for task in self.task_names:
- _results.pop(task)
-
- return wandb_summary, _results
-
- def _log_results_as_table(self) -> None:
- """Generate and log evaluation results as a table to W&B."""
- columns = [
- "Model",
- "Args",
- "Tasks",
- "Version",
- "Filter",
- "num_fewshot",
- "Metric",
- "Value",
- "Stderr",
- ]
-
- def make_table(columns: List[str], key: str = "results"):
- table = wandb.Table(columns=columns)
- results = copy.deepcopy(self.results)
-
- model_name = results.get("model_configs").get("model")
- model_args = results.get("model_configs").get("model_args")
-
- for k, dic in results.get(key).items():
- if k in self.group_names and not key == "groups":
- continue
- version = results.get("versions").get(k)
- if version == "N/A":
- version = None
- n = results.get("n-shot").get(k)
-
- for (mf), v in dic.items():
- m, _, f = mf.partition(",")
- if m.endswith("_stderr"):
- continue
- if m == "alias":
- continue
-
- if m + "_stderr" + "," + f in dic:
- se = dic[m + "_stderr" + "," + f]
- if se != "N/A":
- se = "%.4f" % se
- data = [model_name, model_args, k, version, f, n, m, str(v), str(se)]
- if key == "groups":
- data = [self.group_names] + data
- table.add_data(*data)
- else:
- data = [model_name, model_args, k, version, f, n, m, str(v), ""]
- if key == "groups":
- data = [self.group_names] + data
- table.add_data(*data)
-
- return table
-
- # log the complete eval result to W&B Table
- table = make_table(columns, "results")
- self.run.log({"evaluation/eval_results": table})
-
- if "groups" in self.results.keys():
- table = make_table(["Groups"] + columns, "groups")
- self.run.log({"evaluation/group_eval_results": table})
-
- def _log_results_as_artifact(self) -> None:
- """Log results as JSON artifact to W&B."""
- dumped = json.dumps(self.results, indent=2, default=_handle_non_serializable, ensure_ascii=False)
- artifact = wandb.Artifact("results", type="eval_results")
- with artifact.new_file("results.json", mode="w", encoding="utf-8") as f:
- f.write(dumped)
- self.run.log_artifact(artifact)
-
- def log_eval_result(self) -> None:
- """Log evaluation results to W&B."""
- # Log configs to wandb
- configs = self._get_config()
- self.run.config.update(configs, allow_val_change=True)
-
- wandb_summary, self.wandb_results = self._sanitize_results_dict()
- # update wandb.run.summary with items that were removed
- self.run.summary.update(wandb_summary)
- # Log the evaluation metrics to wandb
- self.run.log(self.wandb_results)
- # Log the evaluation metrics as W&B Table
- self._log_results_as_table()
- # Log the results dict as json to W&B Artifacts
- self._log_results_as_artifact()
-
- def _generate_dataset(self, data: List[Dict[str, Any]], config: Dict[str, Any]) -> pd.DataFrame:
- """Generate a dataset from evaluation data.
-
- Args:
- data (List[Dict[str, Any]]): The data to generate a dataset for.
- config (Dict[str, Any]): The configuration of the task.
-
- Returns:
- pd.DataFrame: A dataframe that is ready to be uploaded to W&B.
- """
- ids = [x["doc_id"] for x in data]
- labels = [x["target"] for x in data]
- instance = [""] * len(ids)
- resps = [""] * len(ids)
- filtered_resps = [""] * len(ids)
- model_outputs = {}
-
- metrics_list = config["metric_list"]
- metrics = {}
- for metric in metrics_list:
- metric = metric.get("metric")
- if metric in ["word_perplexity", "byte_perplexity", "bits_per_byte"]:
- metrics[f"{metric}_loglikelihood"] = [x[metric][0] for x in data]
- if metric in ["byte_perplexity", "bits_per_byte"]:
- metrics[f"{metric}_bytes"] = [x[metric][1] for x in data]
- else:
- metrics[f"{metric}_words"] = [x[metric][1] for x in data]
- else:
- metrics[metric] = [x[metric] for x in data]
-
- if config["output_type"] == "loglikelihood":
- instance = [x["arguments"][0][0] for x in data]
- labels = [x["arguments"][0][1] for x in data]
- resps = [f'log probability of continuation is {x["resps"][0][0][0]} ' + "\n\n" + "continuation will {} generated with greedy sampling".format("not be" if not x["resps"][0][0][1] else "be") for x in data]
- filtered_resps = [f'log probability of continuation is {x["filtered_resps"][0][0]} ' + "\n\n" + "continuation will {} generated with greedy sampling".format("not be" if not x["filtered_resps"][0][1] else "be") for x in data]
- elif config["output_type"] == "multiple_choice":
- instance = [x["arguments"][0][0] for x in data]
- choices = ["\n".join([f"{idx}. {y[1]}" for idx, y in enumerate(x["arguments"])]) for x in data]
- resps = [np.argmax([n[0][0] for n in x["resps"]]) for x in data]
- filtered_resps = [np.argmax([n[0] for n in x["filtered_resps"]]) for x in data]
- elif config["output_type"] == "generate_until":
- instance = [x["arguments"][0][0] for x in data]
- resps = [x["resps"][0][0] for x in data]
- filtered_resps = [x["filtered_resps"][0] for x in data]
-
- model_outputs["raw_predictions"] = resps
- model_outputs["filtered_predictions"] = filtered_resps
-
- df_data = {
- "id": ids,
- "data": instance,
- }
- if config["output_type"] == "multiple_choice":
- df_data["choices"] = choices
-
- tmp_data = {
- "input_len": [len(x) for x in instance],
- "labels": labels,
- "output_type": config["output_type"],
- }
- df_data.update(tmp_data)
- df_data.update(model_outputs)
- df_data.update(metrics)
-
- return pd.DataFrame(df_data)
-
- def _log_samples_as_artifact(self, data: List[Dict[str, Any]], task_name: str) -> None:
- # log the samples as an artifact
- dumped = json.dumps(
- data,
- indent=2,
- default=_handle_non_serializable,
- ensure_ascii=False,
- )
- artifact = wandb.Artifact(f"{task_name}", type="samples_by_task")
- with artifact.new_file(f"{task_name}_eval_samples.json", mode="w", encoding="utf-8") as f:
- f.write(dumped)
- self.run.log_artifact(artifact)
- # artifact.wait()
-
- def log_eval_samples(self, samples: Dict[str, List[Dict[str, Any]]]) -> None:
- """Log evaluation samples to W&B.
-
- Args:
- samples (Dict[str, List[Dict[str, Any]]]): Evaluation samples for each task.
- """
- task_names: List[str] = [x for x in self.task_names if x not in self.group_names]
-
- ungrouped_tasks = []
- tasks_by_groups = {}
-
- for task_name in task_names:
- group_names = self.task_configs[task_name].get("group", None)
- if group_names:
- if isinstance(group_names, str):
- group_names = [group_names]
-
- for group_name in group_names:
- if not tasks_by_groups.get(group_name):
- tasks_by_groups[group_name] = [task_name]
- else:
- tasks_by_groups[group_name].append(task_name)
- else:
- ungrouped_tasks.append(task_name)
-
- for task_name in ungrouped_tasks:
- eval_preds = samples[task_name]
-
- # log the samples as a W&B Table
- df = self._generate_dataset(eval_preds, self.task_configs.get(task_name))
- self.run.log({f"{task_name}_eval_results": df})
-
- # log the samples as a json file as W&B Artifact
- self._log_samples_as_artifact(eval_preds, task_name)
-
- for group, grouped_tasks in tasks_by_groups.items():
- grouped_df = pd.DataFrame()
- for task_name in grouped_tasks:
- eval_preds = samples[task_name]
- df = self._generate_dataset(eval_preds, self.task_configs.get(task_name))
- df["group"] = group
- df["task"] = task_name
- grouped_df = pd.concat([grouped_df, df], ignore_index=True)
-
- # log the samples as a json file as W&B Artifact
- self._log_samples_as_artifact(eval_preds, task_name)
-
- self.run.log({f"{group}_eval_results": grouped_df})
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/models/__init__.py
deleted file mode 100644
index 2c59ea8d02adbaeb027504a6c63d856f6c754509..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/__init__.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from loguru import logger
-import sys
-
-logger.remove()
-logger.add(sys.stdout, level="WARNING")
-
-AVAILABLE_MODELS = {
- "llava": "Llava",
- "qwen_vl": "Qwen_VL",
- "fuyu": "Fuyu",
- "batch_gpt4": "BatchGPT4",
- "gpt4v": "GPT4V",
- "instructblip": "InstructBLIP",
- "minicpm_v": "MiniCPM_V",
- "llava_vid": "LlavaVid",
- "videoChatGPT": "VideoChatGPT",
- "llama_vid": "LLaMAVid",
- "video_llava": "VideoLLaVA",
- "xcomposer2_4KHD": "XComposer2_4KHD",
- "claude": "Claude",
- "qwen_vl_api": "Qwen_VL_API",
- "llava_sglang": "LlavaSglang",
- "idefics2": "Idefics2",
- "internvl": "InternVLChat",
- "gemini_api": "GeminiAPI",
- "reka": "Reka",
- "from_log": "FromLog",
- "mplug_owl_video": "mplug_Owl",
- "phi3v": "Phi3v",
- "tinyllava": "TinyLlava",
- "llava_hf": "LlavaHf",
- "longva": "LongVA",
-}
-
-for model_name, model_class in AVAILABLE_MODELS.items():
- try:
- exec(f"from .{model_name} import {model_class}")
- except ImportError as e:
- # logger.warning(f"Failed to import {model_class} from {model_name}: {e}")
- pass
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/batch_gpt4.py b/lmms-eval-0.2.0.post1/lmms_eval/models/batch_gpt4.py
deleted file mode 100644
index 8f4c22204af5dd95f40b9828b800fa0be462ea3a..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/batch_gpt4.py
+++ /dev/null
@@ -1,204 +0,0 @@
-# Standard library imports
-from copy import deepcopy
-from io import BytesIO
-import base64
-
-import os
-import time
-import json
-
-# Related third-party imports
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-import numpy as np
-from PIL import Image
-import requests as url_requests
-from tqdm import tqdm
-from openai import OpenAI
-
-# Local application/library specific imports
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from loguru import logger as eval_logger
-
-# Conditional imports
-try:
- from decord import VideoReader, cpu
-except ImportError:
- eval_logger.warning("Decord is not installed. Video input will not be supported.")
-
-# Constants and global configurations
-API_TYPE = os.getenv("API_TYPE", "openai")
-NUM_SECONDS_TO_SLEEP = 5
-
-if API_TYPE == "openai":
- API_URL = os.getenv("OPENAI_API_URL", "https://api.openai.com/v1/chat/completions")
- API_KEY = os.getenv("OPENAI_API_KEY", "YOUR_API_KEY")
- headers = {
- "Authorization": f"Bearer {API_KEY}",
- "Content-Type": "application/json",
- }
-elif API_TYPE == "azure":
- API_URL = os.getenv("AZURE_ENDPOINT", "https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
- API_KEY = os.getenv("AZURE_API_KEY", "YOUR_API_KEY")
- headers = {
- "api-key": API_KEY,
- "Content-Type": "application/json",
- }
-else:
- API_URL = "YOUR_API_URL"
- API_KEY = "YOUR_API_KEY"
-
-
-@register_model("batch_gpt4")
-class BatchGPT4(lmms):
- def __init__(
- self,
- model_version: str = "gpt-4o",
- api_key: str = API_KEY,
- api_url: str = API_URL,
- modality: str = "image",
- max_frames_for_video: int = 10,
- timeout: int = 120,
- **kwargs,
- ) -> None:
- super().__init__()
- # Manually set a image token for GPT4V so that we can search for it
- # and split the text and image
- # Here we just use the same token as llava for convenient
- self.model_version = model_version
- self.modality = modality
- self.max_frames_for_video = max_frames_for_video
- self.image_token = ""
- self.timeout = timeout
-
- self.api_key = api_key
- self.api_url = api_url
- self.client = OpenAI(api_key=api_key)
-
- accelerator = Accelerator()
- assert accelerator.state.local_process_index == 0, "BatchGPT4 does not support distributed inference."
- assert accelerator.state.num_processes == 1, "BatchGPT4 does not support distributed inference."
-
- # Function to encode the image
- def encode_image(self, image: Image):
- output_buffer = BytesIO()
- image.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- return base64_str
-
- # Function to encode the video
- def encode_video(self, video_path, for_get_frames_num):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, for_get_frames_num, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- frames = vr.get_batch(frame_idx).asnumpy()
-
- base64_frames = []
- for frame in frames:
- img = Image.fromarray(frame)
- output_buffer = BytesIO()
- img.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- base64_frames.append(base64_str)
-
- return base64_frames
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests):
- # Prepare the batch requests data
- requests_data = {}
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Batch Preparing")
- for idx, (contexts, gen_kwargs, doc_to_visual, doc_id, task, split) in enumerate([reg.args for reg in requests]):
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- imgs = []
- for visual in visuals:
- if self.modality == "image":
- img = self.encode_image(visual)
- imgs.append(img)
- elif self.modality == "video":
- frames = self.encode_video(visual, self.max_frames_for_video)
- imgs.extend(frames)
-
- messages = []
- if self.image_token not in contexts:
- messages.append({"role": "user", "content": contexts})
- for img in imgs:
- messages.append({"role": "user", "content": f"data:image/jpeg;base64,{img}"})
- else:
- contexts_split = contexts.split(self.image_token)
- for idx, context in enumerate(contexts_split):
- if idx < len(imgs):
- messages.append({"role": "user", "content": context})
- messages.append({"role": "user", "content": f"data:image/jpeg;base64,{imgs[idx]}"})
- if len(contexts_split) > len(imgs):
- messages.append({"role": "user", "content": contexts_split[-1]})
-
- requests_data[f"request-{idx}"] = {"model": self.model_version, "messages": messages, "max_tokens": gen_kwargs.get("max_new_tokens", 1024)}
- pbar.update(1)
-
- file_path = os.getenv("HF_HOME", "~/.cache/huggingface") + f"/batchinput_{len(requests_data)}.jsonl"
- file_path = self.create_batch_input_file(requests_data, file_path)
- file_id = self.upload_input_file(file_path)
-
- batch_response = self.create_batch(file_id, metadata={"description": "Batch Processing for GPT-4"})
- batch_status = self.check_batch_status(batch_response.id)
- while True:
- batch_status = self.check_batch_status(batch_response.id)
- if batch_status.status == "completed":
- eval_logger.info("Batch processing completed.")
- batch_results = self.retrieve_batch_results(batch_status.output_file_id)
- res = [result["response"]["choices"][0]["message"]["content"] for result in json.loads(batch_results)]
- return res
- elif batch_status.status == "failed":
- eval_logger.info("Batch processing failed.")
- res = ["Batch failed"] * len(requests)
- return res
- else:
- eval_logger.info(f"Batch status: {batch_status.status}. Retrying in {NUM_SECONDS_TO_SLEEP} seconds.")
- time.sleep(NUM_SECONDS_TO_SLEEP)
-
- def loglikelihood(self, requests):
- # TODO
- assert False, "GPT4V not support"
-
- def create_batch_input_file(self, requests_data, file_path="batchinput.jsonl"):
- with open(file_path, "w") as file:
- for request_id, data in requests_data.items():
- json_record = json.dumps({"custom_id": request_id, "method": "POST", "url": "/v1/chat/completions", "body": data})
- file.write(json_record + "\n")
- return file_path
-
- def upload_input_file(self, file_path):
- with open(file_path, "rb") as file:
- response = self.client.files.create(file=file, purpose="batch")
- return response.id
-
- def create_batch(self, file_id, metadata=None):
- if metadata is None:
- metadata = {}
- response = self.client.batches.create(input_file_id=file_id, endpoint="/v1/chat/completions", completion_window="24h", metadata=metadata)
- return response
-
- def check_batch_status(self, batch_id):
- return self.client.batches.retrieve(batch_id)
-
- def retrieve_batch_results(self, file_id):
- return self.client.files.content(file_id)
-
- def cancel_batch(self, batch_id):
- return self.client.batches.cancel(batch_id)
-
- def list_batches(self, limit=10):
- return self.client.batches.list(limit=limit)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/claude.py b/lmms-eval-0.2.0.post1/lmms_eval/models/claude.py
deleted file mode 100644
index 4c967e8854085823d61b1663c8a841329fc7ba6d..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/claude.py
+++ /dev/null
@@ -1,256 +0,0 @@
-from io import BytesIO
-from copy import deepcopy
-import os
-import base64
-import json
-from typing import List, Tuple, Union
-from tqdm import tqdm
-import time
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-
-from accelerate import Accelerator, DistributedType
-
-from PIL import Image
-
-NUM_SECONDS_TO_SLEEP = 5
-
-from loguru import logger
-
-eval_logger = logger
-
-try:
- import anthropic
- from decord import VideoReader, cpu
- import numpy as np
-except Exception as e:
- eval_logger.warning(f"Error importing claude: {e}")
-
-API_URL = os.getenv("ANTHROPIC_API_URL", "https://api.anthropic.com/v1/complete")
-API_KEY = os.getenv("ANTHROPIC_API_KEY", "YOUR_API_KEY")
-
-
-@register_model("claude")
-class Claude(lmms):
- def __init__(
- self,
- model_version: str = "claude-3-opus-20240229",
- image_token: str = "", # Use to separate interleaved image and text
- system_prompt: str = "", # Whether you want some special system prompt here
- modality: str = "image",
- continual_mode: bool = False,
- response_persistent_folder: str = None,
- **kwargs,
- ) -> None:
- super().__init__()
- self.model_version = model_version
- self.image_token = image_token
- self.system_prompt = system_prompt
- self.modality = modality
-
- self.continual_mode = continual_mode
- if self.continual_mode and response_persistent_folder is None:
- raise ValueError("Continual mode requires a persistent path for the response. Please provide a valid path.")
- self.response_persistent_folder = response_persistent_folder
- self.response_persistent_file = os.path.join(self.response_persistent_folder, f"{self.model_version}_response.json")
-
- if os.path.exists(self.response_persistent_file):
- with open(self.response_persistent_file, "r") as f:
- self.response_cache = json.load(f)
- self.cache_mode = "resume"
- else:
- self.response_cache = {}
- self.cache_mode = "start"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.accelerator = accelerator
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- self.device = self.accelerator.device
-
- def encode_image(self, image):
- output_buffer = BytesIO()
- image.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- return base64_str
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def get_image_size(self, image):
- # Create a BytesIO object to store the image bytes
- img_byte_array = BytesIO()
-
- # Save the image to the BytesIO object
- image.save(img_byte_array, format="PNG")
-
- # Get the size of the BytesIO object
- img_size = img_byte_array.tell()
-
- return img_size
-
- # The max file size is 5MB for claude
- def shrink_image_to_file_size(self, img: Image, max_file_size=4838990) -> Image:
- # Get the current size of the image
- original_size = self.get_image_size(img)
-
- # If the image size is already smaller than the desired size, return
- if original_size <= max_file_size:
- return img
-
- # Calculate the ratio to shrink the image
- # Somehow I found out sqrt ratio is not enough to shrink the image
- # below threshold, so I guess we do more
- shrink_ratio = min(0.9, max_file_size / original_size)
-
- # Resize the image with the calculated ratio
- new_width = int(img.width * shrink_ratio)
- new_height = int(img.height * shrink_ratio)
- img = img.resize((new_width, new_height), Image.LANCZOS)
-
- return self.shrink_image_to_file_size(img, max_file_size)
-
- def encode_video(self, video_path):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.max_frames_for_video, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- frames = vr.get_batch(frame_idx).asnumpy()
-
- base64_frames = []
- for frame in frames:
- img = Image.fromarray(frame)
- output_buffer = BytesIO()
- img.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- base64_frames.append(f"data:image/jpeg;base64,{base64_str}")
-
- return base64_frames
-
- def generate_until(self, requests) -> List[str]:
- client = anthropic.Anthropic()
-
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- empty_image_block = {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": "image/png",
- },
- }
- empty_text_block = {"type": "text"}
- empty_messages = [
- {
- "role": "user",
- "content": [],
- }
- ]
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- ###################### CONTINUAL MODE ######################
- if self.continual_mode is True and self.cache_mode == "resume":
- doc_uuid = f"{task}___{split}___{doc_id}"
- if doc_uuid in self.response_cache:
- response_text = self.response_cache[doc_uuid]
- if response_text:
- res.append(response_text)
- pbar.update(1)
- continue
-
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- imgs = []
- for visual in visuals:
- if isinstance(visual, str) and os.path.exists(visual): # Assuming visual is a path to a video
- visual = self.encode_video(visual)
- for img in visual:
- imgs.append(img)
- else:
- visual = self.shrink_image_to_file_size(visual)
- img = self.encode_image(visual)
- imgs.append(img)
-
- messages = deepcopy(empty_messages)
-
- if self.image_token not in contexts:
- for img in imgs:
- image_block = deepcopy(empty_image_block)
- image_block["source"]["data"] = img
- messages[0]["content"].append(image_block)
- text_block = deepcopy(empty_text_block)
- text_block["text"] = contexts
- messages[0]["content"].append(text_block)
- else:
- contexts = contexts.split(self.image_token)
- for idx, img in enumerate(imgs):
- text_block = deepcopy(empty_text_block)
- image_block = deepcopy(empty_image_block)
- text_block["text"] = contexts
- messages[0]["content"].append(text_block)
- image_block["source"]["data"] = img
- messages[0]["content"].append(image_block)
-
- # If n image tokens are in the contexts
- # contexts will be splitted into n+1 chunks
- # Manually add it into the messages
- text_block = deepcopy(empty_text_block)
- text_block["text"] = contexts
- messages["content"].append(text_block)
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- for attempt in range(5):
- try:
- message = client.messages.create(model=self.model_version, max_tokens=gen_kwargs["max_new_tokens"], system=self.system_prompt, temperature=gen_kwargs["temperature"], top_p=gen_kwargs["top_p"], messages=messages)
- except Exception as e:
- eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
- if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
- time.sleep(NUM_SECONDS_TO_SLEEP)
- else: # If this was the last attempt, log and return empty
- eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
- res.append("")
- pbar.update(1)
- continue
-
- res.append(message.content[0].text)
- pbar.update(1)
-
- ###################### CONTINUAL MODE ######################
- if self.continual_mode is True: # Cache the response
- doc_uuid = f"{task}___{split}___{doc_id}"
- self.response_cache[doc_uuid] = response_text
- with open(self.response_persistent_file, "w") as f:
- json.dump(self.response_cache, f)
-
- pbar.close()
-
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- assert False, "Not supported for claude"
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/from_log.py b/lmms-eval-0.2.0.post1/lmms_eval/models/from_log.py
deleted file mode 100644
index c774a086c87a9f92d3f607c816f4a8b55b3cb963..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/from_log.py
+++ /dev/null
@@ -1,116 +0,0 @@
-import json
-import os
-import re
-
-from datetime import datetime
-from typing import List, Tuple
-from tqdm import tqdm
-from lmms_eval.api.registry import register_model
-from lmms_eval.api.model import lmms
-from lmms_eval.api.instance import Instance
-from accelerate import Accelerator, DistributedType
-
-from loguru import logger as eval_logger
-
-
-@register_model("from_log")
-class FromLog(lmms):
- def __init__(
- self,
- logs: str = "logs",
- model_name: str = None,
- model_args: str = None,
- have_limits: bool = False,
- **kwargs,
- ) -> None:
- super().__init__()
-
- self.logs = {}
-
- log_folders = logs.split(",")
-
- def matched_model(_model_args):
- if model_name and model_name != _model_args["model"]:
- return False
-
- if model_args:
- _model_args_list = model_args.split(",")
-
- for _model_arg in _model_args_list:
- if _model_arg not in _model_args["model_args"]:
- return False
-
- if not have_limits and _model_args["limit"] is not None:
- return False
-
- return True
-
- for log_folder in log_folders:
- for root, dirs, files in os.walk(log_folder):
- for file in files:
- if file.endswith(".json"):
- try:
- log_file = os.path.join(root, file)
-
- with open(log_file, "r") as f:
- log_data = json.load(f)
-
- # check if model is matched
- _model_args = log_data["args"]
- if not matched_model(_model_args):
- raise Exception("Model not matched")
-
- # load logs
- logs = {}
- for data in log_data["logs"]:
- id = data["doc_id"]
- response = data["resps"][0]
- logs[id] = response
-
- task = log_data["model_configs"]["task"]
-
- pattern = re.compile(r"\d{4}_\d{4}")
-
- if "time" in log_data:
- log_time = log_data["time"]
- elif pattern.search(os.path.abspath(log_file)):
- log_time = pattern.findall(os.path.abspath(log_file))[-1]
- else:
- log_time = "unknown"
-
- if task not in self.logs or (self.logs[task]["time"] == "unknown" or datetime.strptime(log_time, "%m%d_%H%M") > datetime.strptime(self.logs[task]["time"], "%m%d_%H%M")):
- self.logs[task] = {"time": log_time, "logs": logs}
-
- except Exception as e:
- pass
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.accelerator = accelerator
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- self.device = self.accelerator.device
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- response = self.logs[task]["logs"][doc_id]
- res.append(response[0])
- pbar.update(1)
-
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "not support"
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/fuyu.py b/lmms-eval-0.2.0.post1/lmms_eval/models/fuyu.py
deleted file mode 100644
index fa108358e756b068da8492222e7396e6523d0d5a..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/fuyu.py
+++ /dev/null
@@ -1,261 +0,0 @@
-import warnings
-
-warnings.simplefilter("ignore", category=DeprecationWarning)
-warnings.filterwarnings("ignore")
-
-from accelerate import Accelerator, DistributedType
-from transformers import FuyuForCausalLM, AutoTokenizer, FuyuImageProcessor, FuyuProcessor
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-import torch
-from PIL import Image
-from typing import List, Optional, Union, Tuple
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from tqdm import tqdm
-from accelerate import Accelerator, DistributedType
-from accelerate.state import AcceleratorState
-
-from loguru import logger as eval_logger
-
-
-@register_model("fuyu")
-class Fuyu(lmms):
- """
- Fuyu Model
- """
-
- def __init__(
- self,
- pretrained: str = "adept/fuyu-8b",
- device: Optional[str] = "cuda",
- max_new_tokens: int = 256,
- batch_size: Optional[Union[int, str]] = 1,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- else:
- self._device = device
-
- self._model = FuyuForCausalLM.from_pretrained(pretrained, torch_dtype=torch.bfloat16, device_map=self.device)
- self.model.eval()
- self.model.tie_weights()
- self._tokenizer = AutoTokenizer.from_pretrained(pretrained)
- self._config = self.model.config
-
- self.image_processor = FuyuImageProcessor()
- self.processor = FuyuProcessor(image_processor=self.image_processor, tokenizer=self.tokenizer)
- self.max_new_tokens = max_new_tokens
- self.batch_size_per_gpu = int(batch_size)
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- """if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [
- DistributedType.FSDP,
- DistributedType.MULTI_GPU,
- ], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- if accelerator.distributed_type == DistributedType.FSDP:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes"""
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- # Assuming max_length is the sum of max context tokens and max new tokens
- return self.tokenizer.model_max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def flatten(self, input, only_get_first=False):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- if only_get_first:
- break
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
-
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals, only_get_first=True)
- gen_kwargs = all_gen_kwargs[0]
-
- # if isinstance(visuals[0], list):
- # visuals = [visuals[idx][0] for idx in range(len(visuals))] # get the first image in multi-image scenarios.
-
- # assert len(contexts) == self.batch_size_per_gpu, f"Expected contexts batch size {self.batch_size_per_gpu}, got {len(contexts)}"
- # assert len(visuals) == self.batch_size_per_gpu, f"Expected visuals batch size {self.batch_size_per_gpu}, got {len(visuals)}"
- formatted_contexts = [f"{context}\n" for context in contexts]
- model_inputs = self.processor(text=formatted_contexts, images=visuals, device=self.device)
- for k, v in model_inputs.items():
- model_inputs[k] = v.to(self.device, non_blocking=True) if isinstance(v, torch.Tensor) else [vv.to(self.device, non_blocking=True) for vv in v]
-
- for index in range(len(model_inputs["image_patches"])):
- model_inputs["image_patches"][index] = model_inputs["image_patches"][index].to(dtype=next(self.model.parameters()).dtype)
-
- # preconfigure gen_kwargs with defaults
- gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 256
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- # generation_output = self.model.generate(
- # **model_inputs, temperature=gen_kwargs["temperature"], max_new_tokens=gen_kwargs["max_new_tokens"], top_p=gen_kwargs["top_p"], num_beams=gen_kwargs["num_beams"], pad_token_id=self.tokenizer.eos_token_id
- # )
- generation_output = self.model.generate(**model_inputs, max_new_tokens=gen_kwargs["max_new_tokens"], pad_token_id=self.tokenizer.eos_token_id)
- generation_texts = self.processor.batch_decode(generation_output, skip_special_tokens=True)
- response = [gen_text.split("\x04")[1].strip(" ").strip("\n") for gen_text in generation_texts]
- res.extend(response)
- pbar.update(1)
-
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- formatted_contexts = [f"{contexts}\n"]
- formatted_continuation = [f"{contexts}\n{continuation}"]
- model_inputs = self.processor(text=formatted_continuation, images=visuals, device=self.device)
- for k, v in model_inputs.items():
- model_inputs[k] = v.to(self.device, non_blocking=True) if isinstance(v, torch.Tensor) else [vv.to(self.device, non_blocking=True) for vv in v]
-
- for index in range(len(model_inputs["image_patches"])):
- model_inputs["image_patches"][index] = model_inputs["image_patches"][index].to(dtype=next(self.model.parameters()).dtype)
-
- labels = model_inputs["input_ids"].clone()
- contxt_id = self.processor(text=formatted_contexts, return_tensors="pt")["input_ids"]
- labels[: len(contxt_id)] = -100
- with torch.inference_mode():
- outputs = self.model(**model_inputs, labels=labels)
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = model_inputs["input_ids"][:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : model_inputs["input_ids"].shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
-
- pbar.close()
- return res
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/gemini_api.py b/lmms-eval-0.2.0.post1/lmms_eval/models/gemini_api.py
deleted file mode 100644
index 4a43c9af464b1ab21150890fe511f45fd146fdf7..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/gemini_api.py
+++ /dev/null
@@ -1,185 +0,0 @@
-import io
-import os
-import time
-
-import json
-
-from PIL import Image
-from typing import List, Tuple
-from tqdm import tqdm
-from lmms_eval.api.registry import register_model
-from lmms_eval.api.model import lmms
-from lmms_eval.api.instance import Instance
-from accelerate import Accelerator, DistributedType
-
-from loguru import logger as eval_logger
-
-try:
- import google.generativeai as genai
- from google.generativeai.types import HarmCategory, HarmBlockThreshold
-
- NUM_SECONDS_TO_SLEEP = 30
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
- genai.configure(api_key=GOOGLE_API_KEY)
-
-except Exception as e:
- eval_logger.error(f"Error importing generativeai: {str(e)}")
- genai = None
-
-
-@register_model("gemini_api")
-class GeminiAPI(lmms):
- def __init__(
- self,
- model_version: str = "gemini-1.5-flash-latest",
- modality: str = "image",
- timeout: int = 120,
- continual_mode: bool = False,
- response_persistent_folder: str = None, # We will cache the Gemini API response in this path and use it for future requests
- **kwargs,
- ) -> None:
- super().__init__()
- self.model_version = model_version
- self.timeout = timeout
- self.model = genai.GenerativeModel(model_version)
- self.continual_mode = continual_mode
- if self.continual_mode and response_persistent_folder is None:
- raise ValueError("Continual mode requires a persistent path for the response. We will cache the Gemini API response in this path and use it for future requests. Please provide a valid path.")
- self.response_persistent_folder = response_persistent_folder
- self.response_persistent_file = os.path.join(self.response_persistent_folder, f"{self.model_version}_response.json")
-
- if os.path.exists(self.response_persistent_file):
- with open(self.response_persistent_file, "r") as f:
- self.response_cache = json.load(f)
- self.cache_mode = "resume"
- else:
- self.response_cache = {}
- self.cache_mode = "start"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- assert self.continual_mode is False, "Continual mode is not supported with distributed inference."
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.accelerator = accelerator
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- self.device = self.accelerator.device
-
- self.modality = modality
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def get_image_size(self, image):
- # Create a BytesIO object to store the image bytes
- img_byte_array = io.BytesIO()
-
- # Save the image to the BytesIO object
- image.save(img_byte_array, format="PNG")
-
- # Get the size of the BytesIO object
- img_size = img_byte_array.tell()
-
- return img_size
-
- def encode_video(self, video_path):
- uploaded_obj = genai.upload_file(path=video_path)
- time.sleep(5)
- return uploaded_obj
-
- def convert_video(self, images):
- for idx, img in enumerate(images):
- if self.modality == "video" and isinstance(img, str):
- try:
- images[idx] = self.encode_video(img)
- except Exception as e:
- eval_logger.error(f"Error converting video: {str(e)}")
- return images
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- def get_uuid(task, split, doc_id):
- return f"{task}___{split}___{doc_id}"
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- if self.continual_mode is True and self.cache_mode == "resume":
- doc_uuid = get_uuid(task, split, doc_id)
- if doc_uuid in self.response_cache:
- content = self.response_cache[doc_uuid]
- if content:
- res.append(content)
- pbar.update(1)
- continue
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
-
- config = genai.GenerationConfig(
- max_output_tokens=gen_kwargs["max_new_tokens"],
- temperature=gen_kwargs["temperature"],
- )
-
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- visuals = self.convert_video(visuals)
-
- message = [contexts] + visuals
-
- for attempt in range(5):
- try:
- content = self.model.generate_content(
- message,
- generation_config=config,
- safety_settings={
- HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
- HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
- HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
- HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
- },
- )
- content = content.text
- break
- except Exception as e:
- eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
- if isinstance(e, ValueError):
- try:
- eval_logger.info(f"Prompt feed_back: {content.prompt_feedback}")
- content = ""
- break
- except Exception:
- pass
- if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
- time.sleep(NUM_SECONDS_TO_SLEEP)
- else: # If this was the last attempt, log and return empty
- eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
- content = ""
- res.append(content)
- pbar.update(1)
-
- if self.continual_mode is True: # Cache the response
- doc_uuid = get_uuid(task, split, doc_id)
- self.response_cache[doc_uuid] = content
- with open(self.response_persistent_file, "w") as f:
- json.dump(self.response_cache, f)
-
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "Gemini API not support"
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/gpt4v.py b/lmms-eval-0.2.0.post1/lmms_eval/models/gpt4v.py
deleted file mode 100644
index 729e73f72901dcd04368b3a397bc6152a9d08b4c..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/gpt4v.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from io import BytesIO
-from copy import deepcopy
-import numpy as np
-import os
-import base64
-from typing import List, Tuple
-from tqdm import tqdm
-import requests as url_requests
-import time
-
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval import utils
-
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-
-try:
- from decord import VideoReader, cpu
-except ImportError:
- pass
-
-from PIL import Image
-
-API_TYPE = os.getenv("API_TYPE", "openai")
-NUM_SECONDS_TO_SLEEP = 30
-from loguru import logger as eval_logger
-
-if API_TYPE == "openai":
- API_URL = os.getenv("OPENAI_API_URL", "https://api.openai.com/v1/chat/completions")
- API_KEY = os.getenv("OPENAI_API_KEY", "YOUR_API_KEY")
- headers = {
- "Authorization": f"Bearer {API_KEY}",
- "Content-Type": "application/json",
- }
-elif API_TYPE == "azure":
- API_URL = os.getenv("AZURE_ENDPOINT", "https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
- API_KEY = os.getenv("AZURE_API_KEY", "YOUR_API_KEY")
- headers = {
- "api-key": API_KEY,
- "Content-Type": "application/json",
- }
-
-
-@register_model("gpt4v")
-class GPT4V(lmms):
- def __init__(
- self,
- model_version: str = "gpt-4-vision-preview",
- modality: str = "video",
- max_frames_for_video: int = 10,
- timeout: int = 120,
- **kwargs,
- ) -> None:
- super().__init__()
- # Manually set a image token for GPT4V so that we can search for it
- # and split the text and image
- # Here we just use the same token as llava for convenient
- self.model_version = model_version
- self.modality = modality
- self.max_frames_for_video = max_frames_for_video
- self.image_token = ""
- self.timeout = timeout
-
- accelerator = Accelerator()
- # assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.accelerator = accelerator
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- self.device = self.accelerator.device
-
- # Function to encode the image
- def encode_image(self, image: Image):
- output_buffer = BytesIO()
- image.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- return base64_str
-
- # Function to encode the video
- def encode_video(self, video_path, for_get_frames_num):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, for_get_frames_num, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- frames = vr.get_batch(frame_idx).asnumpy()
-
- base64_frames = []
- for frame in frames:
- img = Image.fromarray(frame)
- output_buffer = BytesIO()
- img.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- base64_frames.append(base64_str)
-
- return base64_frames
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- # visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = [doc_to_visual(self.task_dict[task][split][0])]
- visuals = self.flatten(visuals)
- imgs = [] # multiple images or frames for video
- for visual in visuals:
- if self.modality == "image":
- img = self.encode_image(visual)
- imgs.append(img)
- elif self.modality == "video":
- frames = self.encode_video(visual, self.max_frames_for_video)
- imgs.extend(frames)
-
- payload = {"model": self.model_version, "messages": []}
- response_json = {"role": "user", "content": []}
- # When there is no image token in the context, append the image to the text
- if self.image_token not in contexts:
- payload["messages"].append(deepcopy(response_json))
- payload["messages"][0]["content"].append({"type": "text", "text": contexts})
- for img in imgs:
- payload["messages"][0]["content"].append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}})
- else:
- contexts = contexts.split(self.image_token)
- for idx, img in enumerate(imgs):
- payload["messages"].append(deepcopy(response_json))
- payload["messages"][idx]["content"].append({"type": "text", "text": contexts[idx]})
- payload["messages"][idx]["content"].append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}})
-
- # If n image tokens are in the contexts
- # contexts will be splitted into n+1 chunks
- # Manually add it into the payload
- payload["messages"].append(deepcopy(response_json))
- payload["messages"][-1]["content"].append({"type": "text", "text": contexts[-1]})
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- payload["max_tokens"] = gen_kwargs["max_new_tokens"]
- payload["temperature"] = gen_kwargs["temperature"]
-
- for attempt in range(5):
- try:
- response = url_requests.post(API_URL, headers=headers, json=payload, timeout=self.timeout)
- response_data = response.json()
-
- content = response_data["choices"][0]["message"]["content"].strip()
- break # If successful, break out of the loop
-
- except Exception as e:
- eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
- if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
- time.sleep(NUM_SECONDS_TO_SLEEP)
- else: # If this was the last attempt, log and return empty
- eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
- eval_logger.error(f"Response: {response}")
- content = ""
- res.append(content)
- pbar.update(1)
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "GPT4V not support"
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/idefics2.py b/lmms-eval-0.2.0.post1/lmms_eval/models/idefics2.py
deleted file mode 100644
index 090cdee5f049f18bd1d4b8c79b394ebbd5103023..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/idefics2.py
+++ /dev/null
@@ -1,231 +0,0 @@
-import torch
-
-from tqdm import tqdm
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from accelerate import Accelerator, DistributedType
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-from transformers import Idefics2ForConditionalGeneration, AutoProcessor
-
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-DEFAULT_IMAGE_TOKEN = ""
-try:
- import flash_attn
-
- best_fit_attn_implementation = "flash_attention_2"
-except ImportError:
- best_fit_attn_implementation = "eager"
-
-
-@register_model("idefics2")
-class Idefics2(lmms):
- """
- Idefics2 Model for Hugging Face Transformers: https://github.com/huggingface/transformers/blob/main/src/transformers/models/idefics2/modeling_idefics2.py
-
- Example usage:
-
- accelerate launch --num_processes=8 -m lmms_eval \
- --model idefics2 \
- --model_args pretrained=HuggingFaceM4/idefics2-8b \
- --tasks mme \
- --batch_size 1 \
- --output_path ./logs/ \
- --log_samples
- """
-
- def __init__(
- self,
- pretrained: str = "HuggingFaceM4/idefics2-8b",
- revision: str = "main",
- device: str = "cuda",
- dtype: Optional[Union[str, torch.dtype]] = "float16",
- batch_size: int = 1,
- trust_remote_code: Optional[bool] = False,
- attn_implementation: Optional[str] = best_fit_attn_implementation,
- device_map: str = "",
- use_cache: bool = True,
- do_image_splitting: bool = False,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1 and device_map == "":
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- else:
- self._device = torch.device(device)
- self.device_map = device_map
- if isinstance(dtype, str) and dtype != "auto":
- dtype = getattr(torch, dtype)
- self._model = Idefics2ForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
- self._processor = AutoProcessor.from_pretrained(pretrained, do_image_splitting=do_image_splitting, revision=revision, trust_remote_code=trust_remote_code)
-
- self._tokenizer = self._processor.tokenizer
- self._config = self._model.config
- self.batch_size_per_gpu = int(batch_size)
- self.use_cache = use_cache
- if accelerator.num_processes > 1 and device_map == "":
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with pipeline parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- raise NotImplementedError("Loglikelihood is not implemented for Idefics2 model")
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visuals, doc_id, tasks, splits = zip(*chunk)
- visuals = [doc_to_visual(self.task_dict[task][split][ids]) for ids, task, split, doc_to_visual in zip(doc_id, tasks, splits, doc_to_visuals)]
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
- #
- until = gen_kwargs.pop("until", None)
- image_aspect_ratio = gen_kwargs.pop("image_aspect_ratio", None)
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
-
- prompts = []
- for context, visual in zip(contexts, visuals):
- content = []
- if DEFAULT_IMAGE_TOKEN not in context:
- for image in visual:
- content.append({"type": "image"})
- content.append({"type": "text", "text": context})
- message = [{"role": "user", "content": content}]
- prompt = self._processor.apply_chat_template(message, add_generation_prompt=True)
- prompts.append(prompt)
- inputs = self._processor(text=prompts, images=visuals, padding=True, return_tensors="pt")
- inputs = {k: v.to(self.device) for k, v in inputs.items()}
- output_ids = self.model.generate(**inputs, **gen_kwargs)
- # only retain the generated text
- for output_id, input_id in zip(output_ids, inputs["input_ids"]):
- generated_id = output_id[len(input_id) :]
- generated_text = self.tokenizer.decode(generated_id, skip_special_tokens=True)
-
- res.append(generated_text)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/instructblip.py b/lmms-eval-0.2.0.post1/lmms_eval/models/instructblip.py
deleted file mode 100644
index c33ab122830b7f9a2ed04abfe6897f733dfd5da0..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/instructblip.py
+++ /dev/null
@@ -1,229 +0,0 @@
-import torch
-
-import copy
-from tqdm import tqdm
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.tasks.mmmu.utils_group_img import process_images
-from accelerate import Accelerator, DistributedType
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-import transformers
-from transformers import InstructBlipProcessor, InstructBlipForConditionalGeneration
-
-from lmms_eval.utils import stop_sequences_criteria
-
-
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-
-@register_model("instructblip")
-class InstructBLIP(lmms):
- """
- InstructBLIP Model
- """
-
- def __init__(
- self,
- pretrained: str = "Salesforce/instructblip-vicuna-7b",
- device: Optional[str] = "cuda",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: Optional[Union[int, str]] = 1,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- else:
- self._device = device
- self._model = InstructBlipForConditionalGeneration.from_pretrained(pretrained, device_map=self._device)
- self._image_processor = InstructBlipProcessor.from_pretrained(pretrained)
- self._tokenizer = self._image_processor.tokenizer
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.batch_size_per_gpu = int(batch_size)
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "We have not implemented this function for InstructBLIP yet"
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals)
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tok_decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
- assert self.batch_size_per_gpu == 1, "Do not support batch_size_per_gpu > 1 for now"
- context = contexts[0]
- if "" in context:
- # instruct blip does not expect the tag
- context = context.replace("", "")
- # Set trunction equals true here, the max length for qformer tokenizer is 512
- # if not truncate, some questions will cause size mismatch
- # The transformer implementation can't handle multi images for blip
- # Concat it into one image
- if len(visuals) > 1:
- visuals = [process_images(visuals)]
- inputs = self._image_processor(images=visuals, text=context, return_tensors="pt", truncation=True).to(self.device)
-
- gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- try:
- cont = self.model.generate(
- **inputs,
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- )
- except Exception as e:
- eval_logger.error(f"Error {e} in generating")
- cont = ""
- text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)[0].strip()
- res.append(text_outputs)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/internvl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/internvl.py
deleted file mode 100644
index 6238d7fcf9196d10cc14ada4bb5efb36296b12e2..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/internvl.py
+++ /dev/null
@@ -1,484 +0,0 @@
-import os
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-import torch
-from tqdm import tqdm
-import numpy as np
-import math
-from datetime import timedelta
-from transformers import AutoConfig
-from huggingface_hub import snapshot_download
-import requests
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.utils import stop_sequences_criteria
-from PIL import Image
-
-import subprocess
-from pathlib import Path
-
-wd = Path(__file__).parent.parent.parent.resolve()
-import sys
-
-sys.path.append(os.path.join(str(wd), "InternVL", "internvl_chat"))
-from loguru import logger as eval_logger
-
-if not hasattr(eval_logger, "internvl_warning_logged"):
- eval_logger.internvl_warning_logged = False
-
-try:
- from internvl.model.internlm2.modeling_internlm2 import InternLM2ForCausalLM
- from internvl.model.internvl_chat.configuration_internvl_chat import InternVLChatConfig
- from internvl.model.internvl_chat.modeling_intern_vit import InternVisionModel
- from internvl.model.internvl_chat import InternVLChatModel
- from internvl.train.dataset import build_transform, dynamic_preprocess
-except ImportError:
- eval_logger.debug("InternVL is not installed. Please install InternVL to use this model.")
- if not eval_logger.internvl_warning_logged:
- eval_logger.debug("InternVL is not installed. Please install InternVL to use this model.")
- eval_logger.internvl_warning_logged = True
-
-import warnings
-from typing import Any, List, Optional, Tuple, Union
-
-import torch.utils.checkpoint
-
-from peft import LoraConfig, get_peft_model
-from torch import nn
-from torch.nn import CrossEntropyLoss
-from transformers import AutoModel, GenerationConfig, LlamaForCausalLM, LlamaTokenizer
-from transformers.modeling_outputs import CausalLMOutputWithPast
-from transformers.modeling_utils import PreTrainedModel
-from transformers import AutoTokenizer
-import re
-from huggingface_hub import snapshot_download
-
-
-@register_model("internvl")
-class InternVLChat(lmms):
- # config_class = InternVLChatConfig
- main_input_name = "pixel_values"
- _no_split_modules = ["InternVisionEncoderLayer", "LlamaDecoderLayer"]
-
- """
- 0. Install lmms-eval
- cd lmms-eval
- pip install -e .
-
- How to Install InternVL:
- 1. Clone the InternVL repository:
- git clone https://github.com/OpenGVLab/InternVL.git
-
- 2. Install the requirements:
- pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118
-
- 3. Install flash-attn==2.3.6:
- pip install flash-attn==2.3.6 --no-build-isolation
- """
-
- """
- How to download the pretrained model:
- 1. Download the pretrained model from hugginface:
- cd pretrained/
- # pip install -U huggingface_hub
- huggingface-cli download --resume-download --local-dir-use-symlinks False OpenGVLab/InternVL-Chat-V1-5 --local-dir InternVL-Chat-V1-5
-
- 2. the pretrained model should be in the following directory:
- pretrained
- └── InternVL-Chat-V1-5
- """
-
- #
- # The above steps can be optional, I add snapshot download, so now can just use hf repo_id
- # model_args pretrained=OpenGVLab/InternVL-Chat-V1-5
- #
-
- """
- InternVL-Chat-V1-5 Model for OpenGVLab https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/internvl/model/internvl_chat/modeling_internvl_chat.py
- Example usage:
-
- accelerate launch --num_processes=8 --main_process_port 12345 -m lmms_eval \
- --model internvl \
- --model_args pretrained=OpenGVLab/InternVL-Chat-V1-5 \
- --tasks llava_wilder_small \
- --batch_size 1 \
- --output_path ./logs/ \
- --log_samples
- """
-
- def __init__(
- self,
- config=None,
- pretrained: str = "OpenGVLab/InternVL-Chat-V1-5",
- truncation: Optional[bool] = True,
- device: Optional[str] = "cuda:0",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: Optional[Union[int, str]] = 1,
- trust_remote_code: Optional[bool] = False,
- revision=None,
- device_map="cuda:0",
- conv_template="vicuna_v1",
- use_cache=True,
- truncate_context=False, # whether to truncate the context in generation, set it False for LLaVA-1.6
- customized_config=None, # ends in json
- dynamic=True,
- load_in_8bit=False,
- vision_model=None,
- language_model=None,
- max_num=12,
- **kwargs,
- ) -> None:
- super().__init__()
-
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- self.dynamic = dynamic # dynamic image_size
- self.max_num = max_num
- if accelerator.is_main_process:
- cache_dir = snapshot_download(repo_id=pretrained, cache_dir="cache_dir", local_dir="cache_dir", local_dir_use_symlinks=False)
- accelerator.wait_for_everyone()
- # So what I did is that I let main process to download the repo, and then
- # other process can just simply read from this repo
- cache_dir = snapshot_download(repo_id=pretrained, cache_dir="cache_dir", local_dir="cache_dir", local_dir_use_symlinks=False)
- config = InternVLChatConfig.from_pretrained(cache_dir)
- tokenizer = AutoTokenizer.from_pretrained(cache_dir, trust_remote_code=True, use_fast=False)
- model = InternVLChatModel.from_pretrained(cache_dir, low_cpu_mem_usage=True, config=config, torch_dtype=torch.bfloat16, load_in_8bit=load_in_8bit).eval()
- if not load_in_8bit:
- model = model.cuda()
- # self.model=model
- # self.device=self._device
- self._tokenizer = tokenizer
- # self.tokenizer=tokenizer
- self._model = model
- self._config = self._model.config
- self.use_thumbnail = self.model.config.use_thumbnail
- self.model.eval()
- self.model.tie_weights()
- self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- self.conv_template = conv_template
- self.use_cache = use_cache
- self.truncate_context = truncate_context
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
-
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- # from internvl model
-
- self.image_size = config.force_image_size or config.vision_config.image_size
-
- def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
- lora_config = LoraConfig(
- r=r,
- target_modules=["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2"],
- lora_alpha=lora_alpha,
- lora_dropout=lora_dropout,
- )
- self.vision_model = get_peft_model(self.vision_model, lora_config)
- self.vision_model.print_trainable_parameters()
-
- def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
- lora_config = LoraConfig(
- r=r, target_modules=["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.down_proj", "mlp.up_proj"], lora_alpha=lora_alpha, lora_dropout=lora_dropout, task_type="CAUSAL_LM"
- )
- self.language_model = get_peft_model(self.language_model, lora_config)
- self.language_model.enable_input_require_grads()
- self.language_model.print_trainable_parameters()
-
- def pixel_shuffle(self, x, scale_factor=0.5):
- n, w, h, c = x.size()
- # N, W, H, C --> N, W, H * scale, C // scale
- x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
- # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
- x = x.permute(0, 2, 1, 3).contiguous()
- # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
- x = x.view(n, int(h * scale_factor), int(w * scale_factor), int(c / (scale_factor * scale_factor)))
- if self.ps_version == "v1":
- warnings.warn("In ps_version 'v1', the height and width have not been swapped back, " "which results in a transposed image.")
- else:
- x = x.permute(0, 2, 1, 3).contiguous()
- return x
-
- def noised_embed(self, vit_embeds, noise_alpha=5):
- dims = torch.tensor(vit_embeds.size(1) * vit_embeds.size(2))
- mag_norm = noise_alpha / torch.sqrt(dims)
- noise = torch.zeros_like(vit_embeds).uniform_(-mag_norm, mag_norm)
- return vit_embeds + noise
-
- def extract_feature(self, pixel_values):
- if self.select_layer == -1:
- vit_embeds = self.vision_model(pixel_values=pixel_values, output_hidden_states=False, return_dict=True).last_hidden_state
- else:
- vit_embeds = self.vision_model(pixel_values=pixel_values, output_hidden_states=True, return_dict=True).hidden_states[self.select_layer]
- vit_embeds = vit_embeds[:, 1:, :]
-
- if self.training and self.neftune_alpha is not None:
- vit_embeds = self.noised_embed(vit_embeds, self.neftune_alpha)
-
- h = w = int(vit_embeds.shape[1] ** 0.5)
- vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
- vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
- vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
- vit_embeds = self.mlp1(vit_embeds) # .to(pixel_values.device)
- return vit_embeds
-
- def multi_image_chat(self, tokenizer, pixel_values, image_counts, question, generation_config, history=None, return_history=False, IMG_START_TOKEN="
", IMG_END_TOKEN="", IMG_CONTEXT_TOKEN=""):
- img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)
- self.img_context_token_id = img_context_token_id
- if tokenizer.convert_tokens_to_ids("<|im_end|>") != 0:
- eos_token_id = tokenizer.convert_tokens_to_ids("<|im_end|>") # 92542, InternLM2
- else:
- eos_token_id = tokenizer.eos_token_id
-
- from internvl.conversation import get_conv_template
-
- template = get_conv_template(self.template)
-
- if history is None:
- history = []
- image_tokens = ""
- image_bs = pixel_values.shape[0]
- # print(f"dynamic ViT batch size: {image_bs}, image_counts: {image_counts}")
- for idx, image_count in enumerate(image_counts):
- image_tokens += f" (图{idx+1}):" + IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * image_count + IMG_END_TOKEN
- question = image_tokens + "\n" + question
- else:
- for old_question, old_answer in history:
- template.append_message(template.roles[0], old_question)
- template.append_message(template.roles[1], old_answer)
- template.append_message(template.roles[0], question)
- template.append_message(template.roles[1], None)
- query = template.get_prompt()
- model_inputs = tokenizer(query, return_tensors="pt")
- input_ids = model_inputs["input_ids"].cuda()
- attention_mask = model_inputs["attention_mask"].cuda()
- generation_config["eos_token_id"] = eos_token_id
-
- generation_output = self.generate(pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask, **generation_config)
- response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
- response = response.split("<|im_end|>")[0].strip() # for InternLM2
- history.append((question, response))
- if return_history:
- return response, history
- else:
- query_to_print = query.replace(image_tokens, "")
- # print(query_to_print, response)
- return response
- return response
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- try:
- return self.tokenizer.decode(tokens)
- except:
- return self.tokenizer.decode([tokens])
-
- def post_processing(self, response):
- response = response.replace("\n", "").replace("不是", "No").replace("是", "Yes").replace("否", "No")
- response = response.lower().replace("true", "yes").replace("false", "no")
- pattern = re.compile(r"[\u4e00-\u9fa5]")
- response = re.sub(pattern, "", response)
- return response
-
- @torch.no_grad()
- def generate(
- self,
- pixel_values: Optional[torch.FloatTensor] = None,
- input_ids: Optional[torch.FloatTensor] = None,
- attention_mask: Optional[torch.LongTensor] = None,
- visual_features: Optional[torch.FloatTensor] = None,
- generation_config: Optional[GenerationConfig] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- **generate_kwargs,
- ) -> torch.LongTensor:
- assert self.img_context_token_id is not None
- if pixel_values is not None:
- if visual_features is not None:
- vit_embeds = visual_features
- else:
- vit_embeds = self.extract_feature(pixel_values)
-
- input_embeds = self.language_model.get_input_embeddings()(input_ids)
- B, N, C = input_embeds.shape
- input_embeds = input_embeds.reshape(B * N, C)
-
- input_ids = input_ids.reshape(B * N)
- selected = input_ids == self.img_context_token_id
- assert selected.sum() != 0
- input_embeds[selected] = vit_embeds.reshape(-1, C).to(input_embeds.device)
-
- input_embeds = input_embeds.reshape(B, N, C)
- else:
- input_embeds = self.language_model.get_input_embeddings()(input_ids)
-
- outputs = self.language_model.generate(
- inputs_embeds=input_embeds,
- attention_mask=attention_mask,
- generation_config=generation_config,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- use_cache=True,
- **generate_kwargs,
- )
-
- return outputs
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def load_image(self, flattened_visuals, input_size=224):
- assert flattened_visuals[0].mode == "RGB"
- image = flattened_visuals[0].convert("RGB")
- transform = build_transform(is_train=False, input_size=input_size)
- if self.dynamic:
- images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=self.use_thumbnail, max_num=self.max_num)
- else:
- images = [image]
- pixel_values = [transform(image) for image in images]
- pixel_values = torch.stack(pixel_values)
- return pixel_values
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- batched_visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id] # [B, N]
- flattened_visuals = self.flatten(batched_visuals)
- pixel_values = self.load_image(flattened_visuals, self.image_size).cuda().to(torch.bfloat16)
- gen_kwargs = all_gen_kwargs[0]
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- generation_config = dict(
- do_sample=False,
- top_k=50,
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- eos_token_id=self.tokenizer.eos_token_id,
- )
- question = contexts[0]
- response = self.model.chat(tokenizer=self.tokenizer, pixel_values=pixel_values, question=question, generation_config=generation_config)
- # TODO(choiszt) try batch_chat for multiple inputs
- response = self.post_processing(response)
- res.append(response)
- self.cache_hook.add_partial("generate_until", (question, gen_kwargs), response)
- pbar.update(1)
- res = re_ords.get_original(res)
- return res
- # print(chunk)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- pass
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/llama_vid.py b/lmms-eval-0.2.0.post1/lmms_eval/models/llama_vid.py
deleted file mode 100644
index e62b4ef7135da17f5f3030da2672958775d81cfc..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/llama_vid.py
+++ /dev/null
@@ -1,271 +0,0 @@
-import os
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-import torch
-from tqdm import tqdm
-from decord import VideoReader, cpu
-import numpy as np
-import math
-from datetime import timedelta
-from transformers import AutoConfig
-from huggingface_hub import snapshot_download
-import requests
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.utils import stop_sequences_criteria
-from lmms_eval.models.model_utils.load_video import read_video_pyav
-
-import subprocess
-
-from loguru import logger as eval_logger
-
-try:
- from llamavid.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
- from llamavid.conversation import conv_templates, SeparatorStyle
- from llamavid.model.builder import load_pretrained_model
- from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
-except ImportError:
- eval_logger.debug("LLaMA-Video is not installed. Please install LLaMA-Video to use this model.")
-
-
-@register_model("llama_vid")
-class LLaMAVid(lmms):
- def __init__(
- self,
- pretrained: str = "YanweiLi/llama-vid-7b-full-224-video-fps-1",
- truncation: Optional[bool] = True,
- device: Optional[str] = "cuda:0",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: Optional[Union[int, str]] = 1,
- trust_remote_code: Optional[bool] = False,
- revision=None,
- attn_implementation=(
- "sdpa" if torch.__version__ > "2.1.2" else "eager"
- ), # inference implementation for attention, can be "sdpa", "eager", "flash_attention_2". Seems FA2 is not effective during inference: https://discuss.huggingface.co/t/flash-attention-has-no-effect-on-inference/73453/5
- device_map="cuda:0",
- conv_template="vicuna_v1",
- use_cache=True,
- truncate_context=False,
- num_frames: int = 100,
- **kwargs,
- ) -> None:
- super().__init__()
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- self.pretrained = pretrained
- self.model_path = snapshot_download(self.pretrained)
- self.model_name = get_model_name_from_path(pretrained)
- self.num_frames = num_frames
- if not os.path.exists("./model_zoo/LAVIS/eva_vit_g.pth") and accelerator.is_main_process:
- eval_logger.info("\n\n Eva Encoder is not found for LLaMA-VID. Download automatically to the folder ./model_zoo/LAVIS")
- cache_path = "model_zoo/LAVIS"
- os.makedirs(cache_path, exist_ok=True)
- subprocess.run(["wget https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/eva_vit_g.pth -O ./model_zoo/LAVIS/eva_vit_g.pth"], shell=True)
-
- accelerator.wait_for_everyone()
- self._tokenizer, self._model, self.image_processor, self._max_length = load_pretrained_model(
- self.model_path,
- None,
- self.model_name,
- device_map=self.device_map,
- )
-
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- self.conv_template = conv_template
- self.use_cache = use_cache
- self.truncate_context = truncate_context
- # assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- def download_file(self, url, folder_path):
- # Create the folder if it doesn't exist
- if not os.path.exists(folder_path):
- os.makedirs(folder_path)
-
- # Extract filename from URL
- filename = url.split("/")[-1]
-
- # Define path to save the file
- file_path = os.path.join(folder_path, filename)
-
- # Send a GET request to the URL
- response = requests.get(url)
-
- # Check if request was successful (status code 200)
- if response.status_code == 200:
- # Save the file to the specified folder
- with open(file_path, "wb") as f:
- f.write(response.content)
- print(f"File downloaded successfully to {file_path}")
- else:
- print(f"Failed to download file. Status code: {response.status_code}")
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def load_video(self, video_path):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- fps = round(vr.get_avg_fps())
- frame_idx = [i for i in range(0, len(vr), fps)]
- spare_frames = vr.get_batch(frame_idx).asnumpy()
- return spare_frames
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- videos = []
- for visual in visuals:
- video = read_video_pyav(visual, num_frm=self.num_frames)
- video = self.image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
- video = [video]
- videos += video
- qs = contexts
- if self.model.config.mm_use_im_start_end:
- qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
- else:
- qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
-
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], qs)
- conv.append_message(conv.roles[1], None)
- prompt = conv.get_prompt()
-
- input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
-
- stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
- keywords = [stop_str]
- stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
-
- cur_prompt = contexts
- with torch.inference_mode():
- self.model.update_prompt([[cur_prompt]])
- output_ids = self.model.generate(input_ids, images=video, do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
-
- input_token_len = input_ids.shape[1]
- n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
- if n_diff_input_output > 0:
- print(f"[Warning] {n_diff_input_output} output_ids are not the same as the input_ids")
- outputs = self.tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
- outputs = outputs.strip()
- if outputs.endswith(stop_str):
- outputs = outputs[: -len(stop_str)]
- outputs = outputs.strip()
- pbar.update(1)
- res.append(outputs)
-
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- return super().loglikelihood(requests)
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/llava.py b/lmms-eval-0.2.0.post1/lmms_eval/models/llava.py
deleted file mode 100644
index 6de4c8f8772eb0b35f6536b348b26c10f98e0292..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/llava.py
+++ /dev/null
@@ -1,419 +0,0 @@
-import torch
-
-torch.backends.cuda.matmul.allow_tf32 = True
-
-
-import copy
-from tqdm import tqdm
-from datetime import timedelta
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.utils import stop_sequences_criteria
-
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-from packaging import version
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-try:
- from llava.model.builder import load_pretrained_model
- from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
- from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
- from llava.conversation import conv_templates
-except Exception as e:
- eval_logger.debug("LLaVA is not installed. Please install LLaVA to use this model.\nError: %s" % e)
-
-# inference implementation for attention, can be "sdpa", "eager", "flash_attention_2". Seems FA2 is not effective during inference: https://discuss.huggingface.co/t/flash-attention-has-no-effect-on-inference/73453/5
-# if is_flash_attn_2_available:
-# best_fit_attn_implementation = "flash_attention_2" # flash_attn has a bug that says: ERROR Error query and key must have the same dtype in generating
-
-if version.parse(torch.__version__) >= version.parse("2.1.2"):
- best_fit_attn_implementation = "sdpa"
-else:
- best_fit_attn_implementation = "eager"
-
-
-@register_model("llava")
-class Llava(lmms):
- """
- Llava Model
- """
-
- def __init__(
- self,
- pretrained: str = "liuhaotian/llava-v1.5-7b",
- truncation: Optional[bool] = True,
- device: Optional[str] = "cuda:0",
- batch_size: Optional[Union[int, str]] = 1,
- model_name=None,
- attn_implementation=best_fit_attn_implementation,
- device_map="cuda:0",
- conv_template="vicuna_v1",
- use_cache=True,
- truncate_context=False, # whether to truncate the context in generation, set it False for LLaVA-1.6
- customized_config=None, # ends in json
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- llava_model_args = {
- "multimodal": True,
- }
- if customized_config is not None:
- llava_model_args["customized_config"] = customized_config
- if attn_implementation is not None:
- llava_model_args["attn_implementation"] = attn_implementation
- if "use_flash_attention_2" in kwargs:
- llava_model_args["use_flash_attention_2"] = kwargs["use_flash_attention_2"]
- model_name = model_name if model_name is not None else get_model_name_from_path(pretrained)
- try:
- # Try to load the model with the multimodal argument
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(pretrained, None, model_name, device_map=self.device_map, **llava_model_args)
- except TypeError:
- # for older versions of LLaVA that don't have multimodal argument
- llava_model_args.pop("multimodal", None)
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(pretrained, None, model_name, device_map=self.device_map, **llava_model_args)
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- self.conv_template = conv_template
- self.use_cache = use_cache
- self.truncate_context = truncate_context
- # assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
-
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- def pad_sequence(self, input_ids, batch_first, padding_value):
- if self.tokenizer.padding_side == "left":
- input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
- input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
- if self.tokenizer.padding_side == "left":
- input_ids = torch.flip(input_ids, [1])
- return input_ids
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- try:
- return self.tokenizer.decode(tokens)
- except:
- return self.tokenizer.decode([tokens])
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- image_sizes = [[visual.size[0], visual.size[1]] for visual in visuals]
- if visuals:
- image = process_images(visuals, self._image_processor, self._config)
- if type(image) is list:
- image = [_image.to(dtype=torch.float16, device=self.device) for _image in image]
- else:
- image = image.to(dtype=torch.float16, device=self.device)
- else:
- image = None
-
- prompts_input = contexts[0] if isinstance(contexts, list) else contexts
-
- if image is not None and len(image) != 0 and DEFAULT_IMAGE_TOKEN not in prompts_input:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- """
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
- image_tokens = " ".join(image_tokens)
- prompts_input = image_tokens + "\n" + (contexts[0] if isinstance(contexts, list) else contexts)
-
- # This is much safer for llama3, as we now have some object type in it
- if "llama_3" in self.conv_template:
- conv = copy.deepcopy(conv_templates[self.conv_template])
- else:
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], prompts_input)
- conv.append_message(conv.roles[1], None)
- prompt = conv.get_prompt()
- pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- contxt_id = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- # Add the answer of the second role
- conv.messages[1][1] = continuation
-
- prompt = conv.get_prompt()
- input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- labels = input_ids.clone()
- # Context part no need to calculate for loss
- labels[0, : contxt_id.shape[1]] = -100
- with torch.inference_mode():
- outputs = self.model(input_ids=input_ids, labels=labels, images=image, use_cache=True, image_sizes=image_sizes)
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = input_ids[:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : input_ids.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
- pbar.close()
- return res
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- batched_visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id] # [B, N]
- flattened_visuals = self.flatten(batched_visuals) # [B*N]
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tok_decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
-
- if "image_aspect_ratio" in gen_kwargs.keys() and "image_aspect_ratio" not in self._config.__dict__:
- # here we should pop it out of gen_kwargs so that it doesn't get passed to the model for next step of generation
- self._config.image_aspect_ratio = gen_kwargs.pop("image_aspect_ratio")
- eval_logger.info(f"Setting image aspect ratio: {self._config.image_aspect_ratio}")
- # encode, pad, and truncate contexts for this batch
- if flattened_visuals:
- image_tensor = process_images(flattened_visuals, self._image_processor, self._config)
- if type(image_tensor) is list:
- image_tensor = [_image.to(dtype=torch.float16, device=self.device) for _image in image_tensor]
- else:
- image_tensor = image_tensor.to(dtype=torch.float16, device=self.device)
- else:
- image_tensor = None
-
- # prompts_input = contexts[0]
-
- question_input = []
-
- for visual, context in zip(batched_visuals, contexts):
- if image_tensor is not None and len(image_tensor) != 0 and DEFAULT_IMAGE_TOKEN not in context:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- """
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visual) if isinstance(visual, list) else [DEFAULT_IMAGE_TOKEN]
- image_tokens = " ".join(image_tokens)
- question = image_tokens + "\n" + context
- else:
- question = context
- # This is much safer for llama3, as we now have some object type in it
- if "llama_3" in self.conv_template:
- conv = copy.deepcopy(conv_templates[self.conv_template])
- else:
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], question)
- conv.append_message(conv.roles[1], None)
- prompt_question = conv.get_prompt()
- question_input.append(prompt_question)
-
- # input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- # preconfigure gen_kwargs with defaults
- gen_kwargs["image_sizes"] = [flattened_visuals[idx].size for idx in range(len(flattened_visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- input_ids_list = [tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt") for prompt in question_input]
- pad_token_ids = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- input_ids = self.pad_sequence(input_ids_list, batch_first=True, padding_value=pad_token_ids).to(self.device)
- attention_masks = input_ids.ne(pad_token_ids).to(self.device)
- # These steps are not in LLaVA's original code, but are necessary for generation to work
- # TODO: attention to this major generation step...
- try:
- cont = self.model.generate(
- input_ids,
- attention_mask=attention_masks,
- pad_token_id=pad_token_ids,
- images=image_tensor,
- image_sizes=gen_kwargs["image_sizes"],
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- use_cache=self.use_cache,
- )
- text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)
- except Exception as e:
- raise e
- eval_logger.error(f"Error {e} in generating")
- cont = ""
- text_outputs = [""]
-
- # cont_toks_list = cont.tolist()
- # for cont_toks, context in zip(cont_toks_list, contexts):
- # discard context + left-padding toks if using causal decoder-only LMM
- # if self.truncate_context:
- # cont_toks = cont_toks[input_ids.shape[1] :]
- # use secondary stop seqs to cut off should-have-been-stopped content post-hoc
- # if self.truncate_context:
- # for term in until:
- # if len(term) > 0:
- # # ignore '' separator,
- # # for seq2seq case where self.tok_decode(self.eot_token_id) = ''
- # text_outputs = text_outputs.split(term)[0]
- res.extend(text_outputs)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_hf.py b/lmms-eval-0.2.0.post1/lmms_eval/models/llava_hf.py
deleted file mode 100644
index 547daa2934054c111aede3064a3d5e7766b181bd..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_hf.py
+++ /dev/null
@@ -1,341 +0,0 @@
-import torch
-
-from tqdm import tqdm
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from accelerate import Accelerator, DistributedType
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-from transformers import LlavaForConditionalGeneration, LlavaNextForConditionalGeneration, AutoProcessor
-
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-DEFAULT_IMAGE_TOKEN = ""
-
-# Default chat for llava-hf/llava-1.5 models: https://huggingface.co/collections/llava-hf/llava-15-65f762d5b6941db5c2ba07e0
-VICUNA_CHAT_TEMPLATE = "{% for message in messages %}{% if loop.index0 == 0 %}A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: {{ message['content'] }} {% elif message['role'] == 'user' %}USER: {{ message['content'] }} {% else %} ASSISTANT: {{ message['content'] }}{{ eos_token }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'ASSISTANT:' }}{% endif %}"
-
-
-@register_model("llava_hf")
-class LlavaHf(lmms):
- """
- Llava Model for Hugging Face Transformers: https://huggingface.co/docs/transformers/v4.39.3/en/model_doc/llava
-
- Adapted from the InstructBLIP model in lmms_eval/models/instructblip.py
-
- Example usage:
-
- accelerate launch --num_processes=8 --main_process_port 12345 -m lmms_eval \
- --model llava_hf \
- --model_args pretrained=llava-hf/llava-1.5-7b-hf \
- --tasks seedbench \
- --batch_size 1 \
- --output_path ./logs/ \
- --log_samples
- """
-
- def __init__(
- self,
- pretrained: str = "llava-hf/llava-1.5-7b-hf",
- revision: str = "main",
- device: str = "cuda",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: int = 1,
- trust_remote_code: Optional[bool] = False,
- attn_implementation: Optional[str] = None,
- device_map: str = "",
- chat_template: Optional[str] = None,
- use_cache: bool = True,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1 and device_map == "":
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- else:
- self._device = torch.device(device)
- self.device_map = device_map
- if isinstance(dtype, str) and dtype != "auto":
- dtype = getattr(torch, dtype)
-
- if "1.5" in pretrained:
- self._model = LlavaForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
- elif "1.6" in pretrained:
- self._model = LlavaNextForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
- else:
- eval_logger.info("Not sure whether you use 1.5 or 1.6. Use 1.5 by default. This might cause bugs if you are actually using 1.6")
- self._model = LlavaForConditionalGeneration.from_pretrained(pretrained, revision=revision, torch_dtype=dtype, device_map=self.device_map, trust_remote_code=trust_remote_code, attn_implementation=attn_implementation)
-
- self.pretrained = pretrained
- self._image_processor = AutoProcessor.from_pretrained(pretrained, revision=revision, trust_remote_code=trust_remote_code)
- # Pad from left for batched generation: https://huggingface.co/docs/transformers/v4.39.3/en/model_doc/llava#usage-tips
- self._image_processor.tokenizer.padding_side = "left"
- self._tokenizer = self._image_processor.tokenizer
- self._config = self._model.config
- self.batch_size_per_gpu = int(batch_size)
- self.chat_template = chat_template
- self.use_cache = use_cache
- if accelerator.num_processes > 1 and device_map == "":
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with pipeline parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
- self.accelerator = accelerator
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for context, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
-
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
- image_tokens = " ".join(image_tokens)
- context = f"{image_tokens}\n{context}"
- # Apply chat template
- messages = [{"role": "user", "content": context}, {"role": "assistant", "content": continuation}]
- if self.chat_template is not None:
- self.tokenizer.chat_template = self.chat_template
- prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
- prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
- elif self.tokenizer.chat_template is not None:
- prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
- prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
- else:
- self.tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
- prompt = self.tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)
- prompt_and_continuation = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
-
- formatted_contexts = [prompt]
- formatted_continuation = [prompt_and_continuation]
- model_inputs = self._image_processor(text=formatted_continuation, images=visuals).to(self._device, self.model.dtype)
- labels = model_inputs["input_ids"].clone()
- contxt_id = self._image_processor(text=formatted_contexts, return_tensors="pt")["input_ids"]
- labels[: len(contxt_id)] = -100
-
- if self.accelerator.is_main_process and doc_id % 100 == 0:
- eval_logger.debug(f"Prompt for doc ID {doc_id}:\n\n{formatted_contexts[0]}\n")
- eval_logger.debug(f"Prompt and continuation for doc ID {doc_id}:\n\n{formatted_continuation[0]}\n")
-
- with torch.inference_mode():
- outputs = self.model(**model_inputs, labels=labels)
- loss = outputs["loss"]
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = model_inputs["input_ids"][:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : model_inputs["input_ids"].shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
-
- pbar.close()
- return res
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals)
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tok_decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
- assert self.batch_size_per_gpu == 1, "Do not support batch_size_per_gpu > 1 for now"
- context = contexts[0]
-
- # Some benchmarks like MME do not contain image tokens, so we prepend them to the prompt.
- if DEFAULT_IMAGE_TOKEN not in context:
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
- image_tokens = " ".join(image_tokens)
- context = f"{image_tokens}\n{context}"
- # Apply chat template
- messages = [{"role": "user", "content": context}]
- if self.chat_template is not None:
- self.tokenizer.chat_template = self.chat_template
- text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
- elif self.tokenizer.chat_template is not None:
- text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
- else:
- self.tokenizer.chat_template = VICUNA_CHAT_TEMPLATE
- text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
-
- if self.accelerator.is_main_process and doc_id[0] % 100 == 0:
- eval_logger.debug(f"Prompt for doc ID {doc_id[0]}:\n\n{text}\n")
-
- inputs = self._image_processor(images=visuals, text=text, return_tensors="pt").to(self._device, self.model.dtype)
-
- gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- try:
- cont = self.model.generate(
- **inputs,
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- use_cache=self.use_cache,
- pad_token_id=self.tokenizer.eos_token_id,
- )
- except Exception as e:
- eval_logger.error(f"Error {e} in generating")
- cont = ""
- text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)[0]
- if "1.5" in self.pretrained:
- text_outputs = text_outputs.split("ASSISTANT:")[-1].strip()
- elif "mistral" in self.pretrained:
- text_outputs = text_outputs.split("[/INST]")[-1].strip()
- else:
- text_outputs = text_outputs.split("ASSISTANT:")[-1].strip()
-
- if self.accelerator.is_main_process and doc_id[0] % 100 == 0:
- eval_logger.debug(f"Generated text for doc ID {doc_id[0]}:\n\n{text_outputs}\n")
-
- res.append(text_outputs)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_sglang.py b/lmms-eval-0.2.0.post1/lmms_eval/models/llava_sglang.py
deleted file mode 100644
index d473e4c1102a56af435b36154dfca20a0741e22e..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_sglang.py
+++ /dev/null
@@ -1,161 +0,0 @@
-import torch
-import random
-
-torch.backends.cuda.matmul.allow_tf32 = True
-
-
-from tqdm import tqdm
-from datetime import timedelta
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-
-from typing import List, Optional, Union, Tuple
-import warnings
-
-warnings.filterwarnings("ignore")
-from concurrent.futures import ThreadPoolExecutor, as_completed
-import tempfile
-
-from loguru import logger as eval_logger
-
-try:
- import sglang as sgl
- from sglang.lang.chat_template import get_chat_template
-except ImportError:
- eval_logger.debug("SGLang is not installed. If you want to use llava_sglang, please install it using pip install 'sglang[all]' ")
-
-if torch.__version__ > "2.1.2":
- best_fit_attn_implementation = "sdpa"
-else:
- best_fit_attn_implementation = "eager"
-
-
-@register_model("llava_sglang")
-class LlavaSglang(lmms):
- """
- Llava Sglang Model
- """
-
- def __init__(
- self,
- pretrained: str = "liuhaotian/llava-v1.5-7b",
- tokenizer: str = "llava-hf/llava-1.5-7b-hf",
- tp_size: int = 1,
- parallel: Optional[Union[int, str]] = 64,
- conv_template="vicuna_v1.1",
- **kwargs,
- ) -> None:
- super().__init__()
- self.pretrained = pretrained
- self.tokenizer = tokenizer
- self.tp_size = tp_size
- self.conv_template = conv_template
- # torch.multiprocessing.set_start_method("spawn")
-
- # accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- # accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- # assert accelerator.num_processes == 1, "Llava-sglang does not support multi-processes yet (it does support tensor parallelism)."
- self._rank = 0
- self._world_size = 1
- self.parallel = parallel
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- raise NotImplementedError("Llava-sglang does not support loglikelihood evaluation yet")
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- torch.multiprocessing.set_start_method("spawn", force=True)
- runtime = sgl.Runtime(model_path=self.pretrained, tokenizer_path=self.tokenizer, tp_size=self.tp_size, port=random.randint(10000, 50000))
- runtime.endpoint.chat_template = get_chat_template(self.conv_template)
- sgl.set_default_backend(runtime)
-
- @sgl.function
- def image_qa(s, image_file, question):
- s += sgl.user(sgl.image(image_file) + question)
- s += sgl.assistant(sgl.gen("answer"))
-
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = x[0].split(" ")
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.parallel, batch_fn=None)
- num_iters = len(requests) // self.parallel if len(requests) % self.parallel == 0 else len(requests) // self.parallel + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visuals, doc_id, tasks, splits = zip(*chunk)
- batched_visuals = [doc_to_visual(self.task_dict[task][split][ids]) for ids, task, split, doc_to_visual in zip(doc_id, tasks, splits, doc_to_visuals)] # [B, N]
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = 1.0
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- assert gen_kwargs["num_beams"] == 1
-
- def save_image_to_temp_file(image):
- temp_file = tempfile.NamedTemporaryFile(suffix=".jpeg", delete=True)
- image.save(temp_file.name)
- return temp_file
-
- def prepare_arguments_parallel(contexts, batched_visuals, max_workers=64):
- arguments = [None] * len(contexts) # Initialize with placeholders
- tmp_files = [None] * len(contexts) # Initialize with placeholders
-
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
- # Associate each future with its index and content
- future_to_info = {executor.submit(save_image_to_temp_file, pil_list[0]): (index, context, pil_list) for index, (context, pil_list) in enumerate(zip(contexts, batched_visuals))}
-
- for future in as_completed(future_to_info):
- index, context, pil_list = future_to_info[future]
- if len(pil_list) > 1:
- eval_logger.warning("Llava-sglang only supports one visual input per question. Using the first visual input.")
- try:
- temp_file = future.result()
- arguments[index] = {
- "image_file": temp_file.name,
- "question": context,
- }
- tmp_files[index] = temp_file
- except Exception as exc:
- print(f"Generated an exception: {exc}")
-
- # Filter out any None values in case of exceptions
- arguments = [arg for arg in arguments if arg is not None]
- tmp_files = [tmp_file for tmp_file in tmp_files if tmp_file is not None]
-
- return arguments, tmp_files
-
- arguments, tmp_files = prepare_arguments_parallel(contexts, batched_visuals, self.parallel)
- states = image_qa.run_batch(arguments, temperature=gen_kwargs["temperature"], max_new_tokens=gen_kwargs["max_new_tokens"], top_p=gen_kwargs["top_p"], num_threads=self.parallel, progress_bar=False)
-
- text_outputs = [state["answer"].strip() for state in states]
- # clean up the temporary files
- for tmp_file in tmp_files:
- tmp_file.close()
- res.extend(text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- runtime.shutdown()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_vid.py b/lmms-eval-0.2.0.post1/lmms_eval/models/llava_vid.py
deleted file mode 100644
index 6188dd95fbe27fb28c49362f32d0f21c50c5a164..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/llava_vid.py
+++ /dev/null
@@ -1,404 +0,0 @@
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-import torch
-from tqdm import tqdm
-from decord import VideoReader, cpu
-import numpy as np
-import math
-from datetime import timedelta
-from transformers import AutoConfig
-import copy
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.models.model_utils.load_video import read_video_pyav
-
-from loguru import logger as eval_logger
-
-try:
- from llavavid.model.builder import load_pretrained_model
- from llavavid.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
- from llavavid.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
- from llavavid.conversation import conv_templates, SeparatorStyle
- from llavavid.mm_utils import tokenizer_image_token_qwen_merge, preprocess_qwen, preprocess_llama3
-except ImportError:
- eval_logger.debug("LLaVA-Video is not installed. Please install LLaVA-Video to use this model.")
-
-from llavavid.model.language_model.llava_qwen import LlavaQwenConfig
-from llavavid.model.language_model.llava_llama import LlavaConfig
-
-AutoConfig.register("llava_qwen", LlavaQwenConfig)
-AutoConfig.register("llava_llama", LlavaConfig)
-
-
-@register_model("llavavid")
-class LlavaVid(lmms):
- """
- LlavaVid Model
- """
-
- def __init__(
- self,
- pretrained: str = "liuhaotian/llava-v1.5-7b",
- truncation: Optional[bool] = True,
- device: Optional[str] = "cuda:0",
- batch_size: Optional[Union[int, str]] = 1,
- attn_implementation=(
- "sdpa" if torch.__version__ >= "2.1.2" else "eager"
- ), # inference implementation for attention, can be "sdpa", "eager", "flash_attention_2". Seems FA2 is not effective during inference: https://discuss.huggingface.co/t/flash-attention-has-no-effect-on-inference/73453/5
- device_map="cuda:0",
- conv_template="vicuna_v1",
- use_cache=True,
- truncate_context=False, # whether to truncate the context in generation, set it False for LLaVA-1.6
- max_frames_num: int = 3,
- mm_resampler_type: str = "spatial_pool",
- mm_spatial_pool_stride: int = 2,
- mm_spatial_pool_out_channels: int = 1024,
- mm_spatial_pool_mode: str = "average",
- overwrite: bool = True,
- video_decode_backend: str = "pyav",
- **kwargs,
- ) -> None:
- super().__init__()
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- self.pretrained = pretrained
- self.model_name = get_model_name_from_path(pretrained)
- self.video_decode_backend = video_decode_backend
- # self._config = AutoConfig.from_pretrained(self.pretrained)
- self.overwrite = overwrite
- self.mm_resampler_type = mm_resampler_type
- self.mm_spatial_pool_stride = int(mm_spatial_pool_stride)
- self.mm_spatial_pool_out_channels = int(mm_spatial_pool_out_channels)
- self.mm_spatial_pool_mode = mm_spatial_pool_mode
- self.max_frames_num = int(max_frames_num)
- if self.overwrite == True:
- overwrite_config = {}
- overwrite_config["mm_resampler_type"] = self.mm_resampler_type
- overwrite_config["mm_spatial_pool_stride"] = self.mm_spatial_pool_stride
- overwrite_config["mm_spatial_pool_out_channels"] = self.mm_spatial_pool_out_channels
- overwrite_config["mm_spatial_pool_mode"] = self.mm_spatial_pool_mode
- overwrite_config["mm_resampler_location"] = "before"
- overwrite_config["patchify_video_feature"] = False
- overwrite_config["attn_implementation"] = attn_implementation
-
- cfg_pretrained = AutoConfig.from_pretrained(self.pretrained)
-
- if cfg_pretrained.architectures[0] == "LlavaLlamaForCausalLM": # Ugly code, only used in vicuna that needs ROPE
- if "224" in cfg_pretrained.mm_vision_tower:
- least_token_number = self.max_frames_num * (16 // self.mm_spatial_pool_stride) ** 2 + 1000
- else:
- least_token_number = self.max_frames_num * (24 // self.mm_spatial_pool_stride) ** 2 + 1000
-
- scaling_factor = math.ceil(least_token_number / 4096)
- if scaling_factor >= 2:
- overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
- overwrite_config["max_sequence_length"] = 4096 * scaling_factor
- overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
-
- if "v1.5" in pretrained: # A hardcode solution here to load v1.5 model, otherwise it will use LlavaConfig from hf transformers
- from transformers import AutoTokenizer
- from llavavid.model.language_model.llava_llama import LlavaConfig, LlavaLlamaForCausalLM
-
- self._tokenizer = AutoTokenizer.from_pretrained(pretrained, use_fast=False)
- cfg_pretrained = LlavaConfig.from_pretrained(pretrained)
- if overwrite_config is not None:
- print(f"Overwriting config with {overwrite_config}")
- for k, v in overwrite_config.items():
- setattr(cfg_pretrained, k, v)
- kwargs["torch_dtype"] = torch.float16
- self._model = LlavaLlamaForCausalLM.from_pretrained(pretrained, low_cpu_mem_usage=True, config=cfg_pretrained, device_map=self.device_map, **kwargs)
- vision_tower = self._model.get_vision_tower()
- if not vision_tower.is_loaded:
- vision_tower.load_model(device_map=self.device_map)
- if self.device_map != "auto":
- vision_tower.to(device="cuda", dtype=torch.float16)
- self._image_processor = vision_tower.image_processor
-
- if hasattr(self._model.config, "max_sequence_length"):
- self._max_length = self._model.config.max_sequence_length
- else:
- self._max_length = 2048
- else:
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(pretrained, None, self.model_name, device_map=self.device_map, overwrite_config=overwrite_config)
- else:
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(
- pretrained,
- None,
- self.model_name,
- device_map=self.device_map,
- )
-
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- self.conv_template = conv_template
- self.use_cache = use_cache
- self.truncate_context = truncate_context
- # assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- def pad_sequence(self, input_ids, batch_first, padding_value):
- if self.tokenizer.padding_side == "left":
- input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
- input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
- if self.tokenizer.padding_side == "left":
- input_ids = torch.flip(input_ids, [1])
- return input_ids
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def load_video(self, video_path, max_frames_num):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- # fps = round(vr.get_avg_fps())
- # frame_idx = [i for i in range(0, len(vr), fps)]
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- spare_frames = vr.get_batch(frame_idx).asnumpy()
- return spare_frames # (frames, height, width, channels)
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- videos = []
- for visual in visuals:
- video = self.load_video(visual, self.max_frames_num)
- video = self._image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
- videos.append(video)
-
- qs = contexts
- if self.model.config.mm_use_im_start_end:
- qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
- else:
- qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
-
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], qs)
- conv.append_message(conv.roles[1], None)
- prompt = conv.get_prompt()
-
- contxt_id = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
-
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], qs)
- conv.append_message(conv.roles[1], continuation)
- prompt = conv.get_prompt()
-
- input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
- attention_masks = input_ids.ne(self.tokenizer.pad_token_id).long().cuda()
-
- labels = input_ids.clone()
- # Context part no need to calculate for loss
- labels[0, : contxt_id.shape[1]] = -100
-
- with torch.inference_mode():
- outputs = self.model(input_ids=input_ids, labels=labels, images=videos, modalities="video")
-
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = input_ids[:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : input_ids.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
- pbar.close()
- return res
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- videos = []
- try:
- for visual in visuals:
- if self.video_decode_backend == "decord":
- video = self.load_video(visual, self.max_frames_num)
- elif self.video_decode_backend == "pyav":
- video = read_video_pyav(visual, num_frm=self.max_frames_num)
- # video = self.load_video(visual, self.max_frames_num)
- video = self._image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
- videos.append(video)
- except Exception as e:
- eval_logger.info(f"{e}")
- eval_logger.info(f"Video {visuals} can not load, check the source")
- video_path = "\n".join(visuals)
- res.append(f"Video {video_path} can not load, check the source")
- pbar.update(1)
- continue
-
- qs = contexts
- if self.model.config.mm_use_im_start_end:
- qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
- else:
- qs = DEFAULT_IMAGE_TOKEN * len(videos) + "\n" + qs
-
- # This is much safer for llama3, as we now have some object type in it
- if "llama_3" in self.conv_template:
- conv = copy.deepcopy(conv_templates[self.conv_template])
- else:
- conv = conv_templates[self.conv_template].copy()
-
- conv.append_message(conv.roles[0], qs)
- conv.append_message(conv.roles[1], None)
- prompt = conv.get_prompt()
-
- input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
- pad_token_ids = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- if "llama_3" in self.conv_template:
- pad_token_ids = 0 # lmms-lab/llama3-llava-8b is trained on this pad token id. You may need to customize this for other models.
- attention_masks = input_ids.ne(pad_token_ids).long().cuda()
-
- stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
- keywords = [stop_str]
- stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
-
- cur_prompt = contexts
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- with torch.inference_mode():
- output_ids = self.model.generate(
- inputs=input_ids,
- images=videos,
- attention_mask=attention_masks,
- modalities="video",
- use_cache=self.use_cache,
- stopping_criteria=[stopping_criteria],
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- )
- # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, use_cache=True, stopping_criteria=[stopping_criteria])
-
- outputs = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
- res.append(outputs)
- pbar.update(1)
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/longva.py b/lmms-eval-0.2.0.post1/lmms_eval/models/longva.py
deleted file mode 100644
index 7202c49ccf8ff0d4e6e797805c7e13e0c1dad376..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/longva.py
+++ /dev/null
@@ -1,462 +0,0 @@
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from transformers import AutoConfig
-
-import math
-import torch
-
-torch.backends.cuda.matmul.allow_tf32 = True
-
-from tqdm import tqdm
-from datetime import timedelta
-from decord import VideoReader, cpu
-import numpy as np
-
-import copy
-import PIL
-from typing import List, Optional, Union, Tuple
-from packaging import version
-import warnings
-import logging
-
-warnings.filterwarnings("ignore")
-
-eval_logger = logging.getLogger("lmms-eval")
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.models.model_utils.load_video import read_video_pyav
-
-try:
- from longva.model.builder import load_pretrained_model
- from longva.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token, KeywordsStoppingCriteria
- from longva.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
- from longva.conversation import conv_templates, SeparatorStyle
-
-except Exception as e:
- eval_logger.debug("longva is not installed. Please install longva to use this model.\nError: %s" % e)
-
-# inference implementation for attention, can be "sdpa", "eager", "flash_attention_2". Seems FA2 is not effective during inference: https://discuss.huggingface.co/t/flash-attention-has-no-effect-on-inference/73453/5
-# if is_flash_attn_2_available:
-# best_fit_attn_implementation = "flash_attention_2" # flash_attn has a bug that says: ERROR Error query and key must have the same dtype in generating
-
-if version.parse(torch.__version__) >= version.parse("2.1.2"):
- best_fit_attn_implementation = "sdpa"
-else:
- best_fit_attn_implementation = "eager"
-
-
-@register_model("longva")
-class LongVA(lmms):
-
- def __init__(
- self,
- pretrained: str = "lmms-lab/LongVA-7B",
- truncation: Optional[bool] = True,
- device: Optional[str] = "cuda:0",
- batch_size: Optional[Union[int, str]] = 1,
- model_name: Optional[str] = None,
- attn_implementation: Optional[str] = best_fit_attn_implementation,
- device_map: Optional[str] = "cuda:0",
- conv_template: Optional[str] = "vicuna_v1",
- use_cache: Optional[bool] = True,
- truncate_context: Optional[bool] = False, # whether to truncate the context in generation, set it False for LLaVA-1.6
- customized_config: Optional[str] = None, # ends in json
- max_frames_num: Optional[int] = 32,
- mm_spatial_pool_stride: Optional[int] = 2,
- mm_spatial_pool_mode: Optional[str] = "average",
- token_strategy: Optional[str] = "single", # could be "single" or "multiple", "multiple" denotes adding multiple tokens for each frame
- video_decode_backend: str = "pyav",
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- llava_model_args = {
- "multimodal": True,
- }
- if customized_config is not None:
- llava_model_args["customized_config"] = customized_config
- if attn_implementation is not None:
- llava_model_args["attn_implementation"] = attn_implementation
- if "use_flash_attention_2" in kwargs:
- llava_model_args["use_flash_attention_2"] = kwargs["use_flash_attention_2"]
- model_name = model_name if model_name is not None else get_model_name_from_path(pretrained)
-
- self.pretrained = pretrained
- self.token_strategy = token_strategy
- self.max_frames_num = max_frames_num
- self.mm_spatial_pool_stride = mm_spatial_pool_stride
- self.mm_spatial_pool_mode = mm_spatial_pool_mode
- self.video_decode_backend = video_decode_backend
-
- overwrite_config = {}
- overwrite_config["mm_spatial_pool_stride"] = self.mm_spatial_pool_stride
- overwrite_config["mm_spatial_pool_mode"] = self.mm_spatial_pool_mode
- cfg_pretrained = AutoConfig.from_pretrained(self.pretrained)
-
- llava_model_args["overwrite_config"] = overwrite_config
- try:
- # Try to load the model with the multimodal argument
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(pretrained, None, model_name, device_map=self.device_map, **llava_model_args)
- except TypeError:
- # for older versions of LLaVA that don't have multimodal argument
- llava_model_args.pop("multimodal", None)
- self._tokenizer, self._model, self._image_processor, self._max_length = load_pretrained_model(pretrained, None, model_name, device_map=self.device_map, **llava_model_args)
-
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- self.conv_template = conv_template
- self.use_cache = use_cache
- self.truncate_context = truncate_context
- assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
-
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
-
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
-
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- def pad_sequence(self, input_ids, batch_first, padding_value):
- if self.tokenizer.padding_side == "left":
- input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
- input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
- if self.tokenizer.padding_side == "left":
- input_ids = torch.flip(input_ids, [1])
- return input_ids
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- try:
- return self.tokenizer.decode(tokens)
- except:
- return self.tokenizer.decode([tokens])
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- image_sizes = [[visual.size[0], visual.size[1]] for visual in visuals]
- if visuals:
- image = process_images(visuals, self._image_processor, self._config)
- if type(image) is list:
- image = [_image.to(dtype=torch.float16, device=self.device) for _image in image]
- else:
- image = image.to(dtype=torch.float16, device=self.device)
- else:
- image = None
-
- prompts_input = contexts[0] if isinstance(contexts, list) else contexts
-
- if image is not None and len(image) != 0 and DEFAULT_IMAGE_TOKEN not in prompts_input:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- """
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
- image_tokens = " ".join(image_tokens)
- prompts_input = image_tokens + "\n" + (contexts[0] if isinstance(contexts, list) else contexts)
-
- # This is much safer for llama3, as we now have some object type in it
- if "llama_3" in self.conv_template:
- conv = copy.deepcopy(conv_templates[self.conv_template])
- else:
- conv = conv_templates[self.conv_template].copy()
-
- conv.append_message(conv.roles[0], prompts_input)
- conv.append_message(conv.roles[1], None)
- prompt = conv.get_prompt()
- pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- contxt_id = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- # Add the answer of the second role
- conv.messages[1][1] = continuation
-
- prompt = conv.get_prompt()
- input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- labels = input_ids.clone()
- # Context part no need to calculate for loss
- labels[0, : contxt_id.shape[1]] = -100
- with torch.inference_mode():
- outputs = self.model(input_ids=input_ids, labels=labels, images=image, use_cache=True, image_sizes=image_sizes)
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = input_ids[:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : input_ids.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
-
- pbar.close()
- return res
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def load_video(self, video_path, max_frames_num):
- if type(video_path) == str:
- vr = VideoReader(video_path, ctx=cpu(0))
- else:
- vr = VideoReader(video_path[0], ctx=cpu(0))
- total_frame_num = len(vr)
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- spare_frames = vr.get_batch(frame_idx).asnumpy()
- return spare_frames # (frames, height, width, channels)
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- batched_contexts, all_gen_kwargs, batched_doc_to_visual, batched_doc_id, batched_task, batched_split = zip(*chunk)
- task = batched_task[0]
- split = batched_split[0]
- batched_visuals = [batched_doc_to_visual[0](self.task_dict[task][split][ids]) for ids in batched_doc_id] # [B, N]
- flattened_visuals = self.flatten(batched_visuals) # [B*N]
- assert len(batched_visuals) == 1
-
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
- if "until" in gen_kwargs:
- gen_kwargs.pop("until")
-
- question_input = []
-
- for visual, context in zip(batched_visuals, batched_contexts):
- if "image_aspect_ratio" in gen_kwargs.keys() and "image_aspect_ratio" not in self._config.__dict__:
- # here we should pop it out of gen_kwargs so that it doesn't get passed to the model for next step of generation
- self._config.image_aspect_ratio = gen_kwargs.pop("image_aspect_ratio")
- eval_logger.info(f"Setting image aspect ratio: {self._config.image_aspect_ratio}")
-
- # encode, pad, and truncate contexts for this batch
- if type(visual[0]) == PIL.Image.Image: # For image task
- image_tensor = process_images(visual, self._image_processor, self._config)
- if type(image_tensor) is list:
- image_tensor = [_image.to(dtype=torch.float16, device=self.device) for _image in image_tensor]
- else:
- image_tensor = image_tensor.to(dtype=torch.float16, device=self.device)
-
- task_type = "image"
-
- elif type(visual[0]) == str: # For video task
- image_tensor = []
- try:
- if self.video_decode_backend == "decord":
- frames = self.load_video(visual, self.max_frames_num)
- elif self.video_decode_backend == "pyav":
- frames = read_video_pyav(visual[0], num_frm=self.max_frames_num)
- frames = self._image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].half().cuda()
- image_tensor.append(frames)
- except Exception as e:
- eval_logger.error(f"Error {e} in loading video")
- image_tensor = None
-
- task_type = "video"
-
- if image_tensor is not None and len(image_tensor) != 0 and DEFAULT_IMAGE_TOKEN not in context:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- 4. For video tasks, we could add a token or multiple tokens for each frame in the context. This depends on the training strategy and should balance in test to decide which is better
- """
- if task_type == "image":
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visual) if isinstance(visual, list) else [DEFAULT_IMAGE_TOKEN]
- elif task_type == "video":
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(frames) if self.token_strategy == "multiple" else [DEFAULT_IMAGE_TOKEN]
-
- image_tokens = " ".join(image_tokens)
- question = image_tokens + "\n" + context
- else:
- question = context
-
- # This is much safer for llama3, as we now have some object type in it
- if "llama_3" in self.conv_template:
- conv = copy.deepcopy(conv_templates[self.conv_template])
- else:
- conv = conv_templates[self.conv_template].copy()
- conv.append_message(conv.roles[0], question)
- conv.append_message(conv.roles[1], None)
- prompt_question = conv.get_prompt()
- question_input.append(prompt_question)
-
- # preconfigure gen_kwargs with defaults
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "do_sample" not in gen_kwargs:
- gen_kwargs["do_sample"] = False
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- input_ids_list = [tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt") for prompt in question_input]
- pad_token_ids = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- input_ids = self.pad_sequence(input_ids_list, batch_first=True, padding_value=pad_token_ids).to(self.device)
- attention_masks = input_ids.ne(pad_token_ids).to(self.device)
-
- if task_type == "image":
- gen_kwargs["image_sizes"] = [flattened_visuals[idx].size for idx in range(len(flattened_visuals))]
- elif task_type == "video":
- stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
- keywords = [stop_str]
- stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
- gen_kwargs["modalities"] = ["video"]
- gen_kwargs["stopping_criteria"] = [stopping_criteria]
- self._config.mm_spatial_pool_stride = self.mm_spatial_pool_stride
- self._config.mm_spatial_pool_mode = self.mm_spatial_pool_mode
-
- # These steps are not in LLaVA's original code, but are necessary for generation to work
- # TODO: attention to this major generation step...
- if "image_aspect_ratio" in gen_kwargs.keys():
- gen_kwargs.pop("image_aspect_ratio")
- try:
- with torch.inference_mode():
- cont = self.model.generate(input_ids, attention_mask=attention_masks, pad_token_id=pad_token_ids, images=image_tensor, use_cache=self.use_cache, **gen_kwargs)
-
- text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)
- except Exception as e:
- raise e
-
- text_outputs = [response.strip() for response in text_outputs]
- res.extend(text_outputs)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
\ No newline at end of file
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/minicpm_v.py b/lmms-eval-0.2.0.post1/lmms_eval/models/minicpm_v.py
deleted file mode 100644
index 9a6e0215985179cf5dacee8ff8564f6d2cc34c53..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/minicpm_v.py
+++ /dev/null
@@ -1,222 +0,0 @@
-import torch
-
-from tqdm import tqdm
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from accelerate import Accelerator, DistributedType
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-from transformers import AutoModel, AutoTokenizer
-
-
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-
-@register_model("minicpm_v")
-class MiniCPM_V(lmms):
- """
- MiniCPM_V Model
- """
-
- def __init__(
- self,
- pretrained: str = "openbmb/MiniCPM-V",
- device: Optional[str] = "cuda",
- dtype: Optional[Union[str, torch.dtype]] = torch.bfloat16,
- batch_size: Optional[Union[int, str]] = 1,
- trust_remote_code: Optional[bool] = True,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- else:
- self._device = device
- self._model = AutoModel.from_pretrained(pretrained, trust_remote_code=trust_remote_code, torch_dtype=dtype, device_map=self._device).to(dtype)
- self._tokenizer = AutoTokenizer.from_pretrained(pretrained, trust_remote_code=trust_remote_code)
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- self.batch_size_per_gpu = int(batch_size)
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- return self.tokenizer.decode(tokens)
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "We have not implemented this function for MiniCPM_V yet"
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals)
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tok_decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
- assert self.batch_size_per_gpu == 1, "Do not support batch_size_per_gpu > 1 for now"
- assert len(visuals) == 1, "MiniCPM_V interface does not support bn_image > 1 for now"
- context = contexts[0]
- if "" in context:
- # minicpm does not expect the tag
- context = context.replace("", "")
- msgs = [{"role": "user", "content": context}]
-
- gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- try:
- # ominicpm does not give much information on how they do eval so I just use the chat format.
- response, context, _ = self.model.chat(
- image=visuals[0],
- msgs=msgs,
- context=None,
- tokenizer=self.tokenizer,
- sampling=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- )
- except Exception as e:
- eval_logger.error(f"Error {e} in generating")
- cont = ""
- res.append(response)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), response)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/load_video.py b/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/load_video.py
deleted file mode 100644
index 789039e7acaba4e57ccfeab7d187224c54bba8cf..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/load_video.py
+++ /dev/null
@@ -1,55 +0,0 @@
-import av
-from av.codec.context import CodecContext
-import numpy as np
-
-
-# This one is faster
-def record_video_length_stream(container, indices):
- frames = []
- start_index = indices[0]
- end_index = indices[-1]
- for i, frame in enumerate(container.decode(video=0)):
- if i > end_index:
- break
- if i >= start_index and i in indices:
- frames.append(frame)
- return frames
-
-
-# This one works for all types of video
-def record_video_length_packet(container):
- frames = []
- # https://github.com/PyAV-Org/PyAV/issues/1269
- # https://www.cnblogs.com/beyond-tester/p/17641872.html
- # context = CodecContext.create("libvpx-vp9", "r")
- for packet in container.demux(video=0):
- for frame in packet.decode():
- frames.append(frame)
- return frames
-
-
-def read_video_pyav(video_path, num_frm=8):
-
- if "webm" not in video_path and "mkv" not in video_path:
- # For mp4, we try loading with stream first
- try:
- container = av.open(video_path)
- total_frames = container.streams.video[0].frames
- sampled_frm = min(total_frames, num_frm)
- indices = np.linspace(0, total_frames - 1, sampled_frm, dtype=int)
- frames = record_video_length_stream(container, indices)
- except:
- container = av.open(video_path)
- frames = record_video_length_packet(container)
- total_frames = len(frames)
- sampled_frm = min(total_frames, num_frm)
- indices = np.linspace(0, total_frames - 1, sampled_frm, dtype=int)
- frames = [frames[i] for i in indices]
- else:
- container = av.open(video_path)
- frames = record_video_length_packet(container)
- total_frames = len(frames)
- sampled_frm = min(total_frames, num_frm)
- indices = np.linspace(0, total_frames - 1, sampled_frm, dtype=int)
- frames = [frames[i] for i in indices]
- return np.stack([x.to_ndarray(format="rgb24") for x in frames])
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/qwen/qwen_generate_utils.py b/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/qwen/qwen_generate_utils.py
deleted file mode 100644
index 3717665a05b11f7d883af06d4eb376d8fb4c31ba..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/model_utils/qwen/qwen_generate_utils.py
+++ /dev/null
@@ -1,370 +0,0 @@
-# Copyright (c) Alibaba Cloud.
-#
-# This source code is licensed under the license found in the
-# LICENSE file in the root directory of this source tree.
-
-"""Generation support."""
-import warnings
-
-warnings.simplefilter("ignore", category=DeprecationWarning)
-warnings.filterwarnings("ignore")
-
-from typing import Tuple, List, Union, Iterable
-
-import numpy as np
-import torch
-import torch.nn.functional as F
-from transformers import PreTrainedTokenizer
-from transformers.generation import LogitsProcessor
-
-from loguru import logger
-
-# Types.
-HistoryType = List[Tuple[str, str]]
-TokensType = List[int]
-BatchTokensType = List[List[int]]
-
-
-def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
- for tokens in batch:
- context_length = len(tokens)
- if context_length < seq_length:
- tokens.extend([pad_id] * (seq_length - context_length))
- return batch
-
-
-def get_ltor_masks_and_position_ids(
- data,
- eod_token,
- reset_position_ids,
- reset_attention_mask,
- eod_mask_loss,
-):
- """Build masks and position id for left to right model."""
-
- # Extract batch size and sequence length.
- micro_batch_size, seq_length = data.size()
-
- # Attention mask (lower triangular).
- if reset_attention_mask:
- att_mask_batch = micro_batch_size
- else:
- att_mask_batch = 1
- attention_mask = torch.tril(torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)).view(att_mask_batch, 1, seq_length, seq_length)
-
- # Loss mask.
- loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
- if eod_mask_loss:
- loss_mask[data == eod_token] = 0.0
-
- # Position ids.
- position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
- position_ids = position_ids.unsqueeze(0).expand_as(data)
- # We need to clone as the ids will be modifed based on batch index.
- if reset_position_ids:
- position_ids = position_ids.clone()
-
- if reset_position_ids or reset_attention_mask:
- # Loop through the batches:
- for b in range(micro_batch_size):
- # Find indecies where EOD token is.
- eod_index = position_ids[b, data[b] == eod_token]
- # Detach indecies from positions if going to modify positions.
- if reset_position_ids:
- eod_index = eod_index.clone()
-
- # Loop through EOD indecies:
- prev_index = 0
- for j in range(eod_index.size()[0]):
- i = eod_index[j]
- # Mask attention loss.
- if reset_attention_mask:
- attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
- # Reset positions.
- if reset_position_ids:
- position_ids[b, (i + 1) :] -= i + 1 - prev_index
- prev_index = i + 1
-
- # Convert attention mask to binary:
- attention_mask = attention_mask < 0.5
-
- return attention_mask, loss_mask, position_ids
-
-
-def get_batch(context_tokens: torch.LongTensor, eod_id: int):
- """Generate batch from context tokens."""
- # Move to GPU.
- tokens = context_tokens.contiguous().to(context_tokens.device)
- # Get the attention mask and postition ids.
- attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
- tokens,
- eod_id,
- reset_position_ids=False,
- reset_attention_mask=False,
- eod_mask_loss=False,
- )
- return tokens, attention_mask, position_ids
-
-
-def get_stop_words_ids(chat_format, tokenizer):
- if chat_format == "raw":
- stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
- elif chat_format == "chatml":
- stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
- else:
- raise NotImplementedError(f"Unknown chat format {chat_format!r}")
- return stop_words_ids
-
-
-def make_context(
- tokenizer: PreTrainedTokenizer,
- query: str,
- history: List[Tuple[str, str]] = None,
- system: str = "",
- max_window_size: int = 6144,
- chat_format: str = "chatml",
-):
- if history is None:
- history = []
-
- if chat_format == "chatml":
- im_start, im_end = "<|im_start|>", "<|im_end|>"
- im_start_tokens = [tokenizer.im_start_id]
- im_end_tokens = [tokenizer.im_end_id]
- nl_tokens = tokenizer.encode("\n")
-
- def _tokenize_str(role, content):
- return f"{role}\n{content}", tokenizer.encode(role, allowed_special=set(tokenizer.IMAGE_ST)) + nl_tokens + tokenizer.encode(content, allowed_special=set(tokenizer.IMAGE_ST))
-
- system_text, system_tokens_part = _tokenize_str("system", system)
- system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
-
- raw_text = ""
- context_tokens = []
-
- for turn_query, turn_response in reversed(history):
- query_text, query_tokens_part = _tokenize_str("user", turn_query)
- query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
- if turn_response is not None:
- response_text, response_tokens_part = _tokenize_str("assistant", turn_response)
- response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
-
- next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
- prev_chat = f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
- else:
- next_context_tokens = nl_tokens + query_tokens + nl_tokens
- prev_chat = f"\n{im_start}{query_text}{im_end}\n"
-
- current_context_size = len(system_tokens) + len(next_context_tokens) + len(context_tokens)
- if current_context_size < max_window_size:
- context_tokens = next_context_tokens + context_tokens
- raw_text = prev_chat + raw_text
- else:
- break
-
- context_tokens = system_tokens + context_tokens
- raw_text = f"{im_start}{system_text}{im_end}" + raw_text
- context_tokens += nl_tokens + im_start_tokens + _tokenize_str("user", query)[1] + im_end_tokens + nl_tokens + im_start_tokens + tokenizer.encode("assistant") + nl_tokens
- raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
-
- elif chat_format == "raw":
- raw_text = query
- context_tokens = tokenizer.encode(raw_text)
- else:
- raise NotImplementedError(f"Unknown chat format {chat_format!r}")
-
- return raw_text, context_tokens
-
-
-def _decode_default(
- tokens: List[int],
- *,
- stop_words: List[str],
- eod_words: List[str],
- tokenizer: PreTrainedTokenizer,
- raw_text_len: int,
- verbose: bool = False,
- return_end_reason: bool = False,
- errors: str = "replace",
-):
- trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
- if verbose:
- print("\nRaw Generate: ", trim_decode_tokens)
-
- end_reason = f"Gen length {len(tokens)}"
- for stop_word in stop_words:
- trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
- for eod_word in eod_words:
- if eod_word in trim_decode_tokens:
- end_reason = f"Gen {eod_word!r}"
- trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
- trim_decode_tokens = trim_decode_tokens.strip()
- if verbose:
- print("\nEnd Reason:", end_reason)
- print("\nGenerate: ", trim_decode_tokens)
-
- if return_end_reason:
- return trim_decode_tokens, end_reason
- else:
- return trim_decode_tokens
-
-
-def _decode_chatml(
- tokens: List[int], *, stop_words: List[str], eod_token_ids: List[int], tokenizer: PreTrainedTokenizer, raw_text_len: int, context_length: int, verbose: bool = False, return_end_reason: bool = False, errors: str = "replace"
-):
- end_reason = f"Gen length {len(tokens)}"
- eod_token_idx = context_length
- for eod_token_idx in range(context_length, len(tokens)):
- if tokens[eod_token_idx] in eod_token_ids:
- end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
- break
-
- trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
- if verbose:
- print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
- print("\nRaw Generate:", trim_decode_tokens)
- print("\nEnd Reason:", end_reason)
- for stop_word in stop_words:
- trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
- trim_decode_tokens = trim_decode_tokens.strip()
- if verbose:
- print("\nGenerate:", trim_decode_tokens)
-
- if return_end_reason:
- return trim_decode_tokens, end_reason
- else:
- return trim_decode_tokens
-
-
-def decode_tokens(
- tokens: Union[torch.LongTensor, TokensType],
- tokenizer: PreTrainedTokenizer,
- raw_text_len: int,
- context_length: int,
- chat_format: str,
- verbose: bool = False,
- return_end_reason: bool = False,
- errors: str = "replace",
-) -> str:
- if torch.is_tensor(tokens):
- tokens = tokens.cpu().numpy().tolist()
-
- if chat_format == "chatml":
- return _decode_chatml(
- tokens,
- stop_words=[],
- eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
- tokenizer=tokenizer,
- raw_text_len=raw_text_len,
- context_length=context_length,
- verbose=verbose,
- return_end_reason=return_end_reason,
- errors=errors,
- )
- elif chat_format == "raw":
- return _decode_default(
- tokens,
- stop_words=["<|endoftext|>"],
- eod_words=["<|endoftext|>"],
- tokenizer=tokenizer,
- raw_text_len=raw_text_len,
- verbose=verbose,
- return_end_reason=return_end_reason,
- errors=errors,
- )
- else:
- raise NotImplementedError(f"Unknown chat format {chat_format!r}")
-
-
-class StopWordsLogitsProcessor(LogitsProcessor):
- """
- :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
- Args:
- stop_words_ids (:obj:`List[List[int]]`):
- List of list of token ids of stop ids. In order to get the tokens of the words
- that should not appear in the generated text, use :obj:`tokenizer(bad_word,
- add_prefix_space=True).input_ids`.
- eos_token_id (:obj:`int`):
- The id of the `end-of-sequence` token.
- """
-
- def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
- if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
- raise ValueError(f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}.")
- if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
- raise ValueError(f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}.")
- if any(any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in stop_word_ids) for stop_word_ids in stop_words_ids):
- raise ValueError(f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}.")
-
- self.stop_words_ids = list(filter(lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids))
- self.eos_token_id = eos_token_id
- for stop_token_seq in self.stop_words_ids:
- assert len(stop_token_seq) > 0, "Stop words token sequences {} cannot have an empty list".format(stop_words_ids)
-
- def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
- stopped_samples = self._calc_stopped_samples(input_ids)
- for i, should_stop in enumerate(stopped_samples):
- if should_stop:
- scores[i, self.eos_token_id] = float(2**15)
- return scores
-
- def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
- if len(tokens) == 0:
- # if bad word tokens is just one token always ban it
- return True
- elif len(tokens) > len(prev_tokens):
- # if bad word tokens are longer then prev input_ids they can't be equal
- return False
- elif prev_tokens[-len(tokens) :].tolist() == tokens:
- # if tokens match
- return True
- else:
- return False
-
- def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
- stopped_samples = []
- for prev_input_ids_slice in prev_input_ids:
- match = False
- for stop_token_seq in self.stop_words_ids:
- if self._tokens_match(prev_input_ids_slice, stop_token_seq):
- # if tokens do not match continue
- match = True
- break
- stopped_samples.append(match)
-
- return stopped_samples
-
-
-def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
- """This function has been mostly taken from huggingface conversational
- ai code at
- https://medium.com/huggingface/how-to-build-a-state-of-the-art-
- conversational-ai-with-transfer-learning-2d818ac26313"""
-
- if top_k > 0:
- # Remove all tokens with a probability less than the
- # last token of the top-k
- indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
- logits[indices_to_remove] = filter_value
-
- if top_p > 0.0:
- # Cconvert to 1D
- sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
- cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
-
- # Remove tokens with cumulative probability above the threshold
- sorted_indices_to_remove = cumulative_probs > top_p
- # Shift the indices to the right to keep also the first token
- # above the threshold
- sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
- sorted_indices_to_remove[..., 0] = 0
- for i in range(sorted_indices.size(0)):
- indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
- logits[i][indices_to_remove] = filter_value
-
- return logits
-
-
-def switch(val1, val2, boolean):
- boolean = boolean.type_as(val1)
- return (1 - boolean) * val1 + boolean * val2
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video.py
deleted file mode 100644
index 1055f4dd6900a15242da4969ae8760fb7ff7f88b..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video.py
+++ /dev/null
@@ -1,193 +0,0 @@
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-import torch
-from transformers import AutoTokenizer
-from tqdm import tqdm
-from datetime import timedelta
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-
-from lmms_eval.models.mplug_owl_video.modeling_mplug_owl import MplugOwlForConditionalGeneration
-from lmms_eval.models.mplug_owl_video.processing_mplug_owl import MplugOwlImageProcessor, MplugOwlProcessor
-
-
-from loguru import logger
-
-eval_logger = logger
-
-
-@register_model("mplug_owl_video")
-class mplug_Owl(lmms):
- def __init__(
- self,
- pretrained: str = "MAGAer13/mplug-owl-llama-7b-video",
- device: Optional[str] = "cuda:0",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: Optional[Union[int, str]] = 1,
- device_map="cuda:0",
- num_frames: Union[str, int] = 4,
- **kwargs,
- ) -> None:
- """
- Install instructions:
- 1. Install lmms-eval
- cd lmms-eval
- pip install -e .;
- 2. Install other packages with restricted versions
- pip install av sentencepiece protobuf==3.20 transformers==4.28.1 einops;
- """
- super().__init__()
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- # import pdb; pdb.set_trace()
- # This is very slow. Their issue, not mine
- # Also, keep transformers in version 4.28.1
- # They put a Config object inside a config object, this is not acceptable
- # for transformers == 4.39.1, object type not serializable
- # Protobuf needs to be in 3.20.x otherwise error
- # ヽ(`Д´)ノ
- self._model = MplugOwlForConditionalGeneration.from_pretrained(
- pretrained,
- torch_dtype=torch.bfloat16,
- )
- self.image_processor = MplugOwlImageProcessor.from_pretrained(pretrained)
- self._tokenizer = AutoTokenizer.from_pretrained(pretrained)
- self.processor = MplugOwlProcessor(self.image_processor, self.tokenizer)
- self.model.eval()
- self.batch_size_per_gpu = batch_size
- self.num_frames = num_frames
-
- self.model.to(self.device)
-
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def format_prompt(self, question):
- prompts = [f" <|video|> Question : {question} Answer : "]
- return prompts
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- inputs = self.processor(text=self.format_prompt(contexts), videos=visuals, num_frames=self.num_frames, return_tensors="pt")
- pixel_values_videos = inputs["video_pixel_values"]
- if pixel_values_videos.shape[2] != self.num_frames:
- empty_frames = torch.zeros((1, pixel_values_videos.shape[1], self.num_frames - pixel_values_videos.shape[2], *pixel_values_videos.shape[3:]), dtype=pixel_values_videos.dtype)
- pixel_values_videos = torch.cat([pixel_values_videos, empty_frames], dim=2)
- inputs["video_pixel_values"] = pixel_values_videos
- inputs = {k: v.bfloat16() if v.dtype == torch.float else v for k, v in inputs.items()}
- inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
-
- if "max_new_tokens" in gen_kwargs:
- gen_kwargs["max_length"] = gen_kwargs["max_new_tokens"]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_length"] = 128
- if "do_sample" not in gen_kwargs:
- gen_kwargs["do_sample"] = False
- if "top_k" not in gen_kwargs:
- gen_kwargs["top_k"] = 1
-
- generate_kwargs = {"do_sample": gen_kwargs["do_sample"], "top_k": gen_kwargs["top_k"], "max_length": gen_kwargs["max_length"]}
-
- with torch.no_grad():
- outputs = self.model.generate(**inputs, **generate_kwargs)
- sentence = self.tokenizer.decode(outputs.tolist()[0], skip_special_tokens=True)
- pbar.update(1)
- res.append(sentence)
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- return super().loglikelihood(requests)
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/__init__.py
deleted file mode 100644
index 2020ad3a8823c87d70054ba386129e9b17fc5c22..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/__init__.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# Copyright 2020 The HuggingFace Team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-from typing import TYPE_CHECKING
-
-from transformers.utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
-
-
-_import_structure = {
- "configuration_mplug_owl": ["MPLUG_OWL_PRETRAINED_CONFIG_ARCHIVE_MAP", "MplugOwlConfig"],
- "processing_mplug_owl": ["MplugOwlImageProcessor", "MplugOwlProcessor"],
- "tokenization_mplug_owl": ["MplugOwlTokenizer"],
-}
-
-try:
- if not is_tokenizers_available():
- raise OptionalDependencyNotAvailable()
-except OptionalDependencyNotAvailable:
- pass
-
-
-try:
- if not is_torch_available():
- raise OptionalDependencyNotAvailable()
-except OptionalDependencyNotAvailable:
- pass
-else:
- _import_structure["modeling_mplug_owl"] = [
- "MPLUG_OWL_PRETRAINED_MODEL_ARCHIVE_LIST",
- "MplugOwlForConditionalGeneration",
- "MplugOwlModel",
- ]
-
-
-if TYPE_CHECKING:
- from .configuration_mplug_owl import MPLUG_OWL_PRETRAINED_CONFIG_ARCHIVE_MAP, MplugOwlConfig
- from .tokenization_mplug_owl import MplugOwlTokenizer
-
- try:
- if not is_tokenizers_available():
- raise OptionalDependencyNotAvailable()
- except OptionalDependencyNotAvailable:
- pass
-
- try:
- if not is_torch_available():
- raise OptionalDependencyNotAvailable()
- except OptionalDependencyNotAvailable:
- pass
- else:
- from .modeling_mplug_owl import (
- MPLUG_OWL_PRETRAINED_MODEL_ARCHIVE_LIST,
- MplugOwlForConditionalGeneration,
- MplugOwlModel,
- MplugOwlPreTrainedModel,
- )
-
-
-else:
- import sys
-
- sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
-
-from .configuration_mplug_owl import *
-from .modeling_mplug_owl import *
-from .processing_mplug_owl import *
-from .tokenization_mplug_owl import *
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/configuration_mplug_owl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/configuration_mplug_owl.py
deleted file mode 100644
index ce5b777bb42a53db8d45d7aa96664144b96692c0..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/configuration_mplug_owl.py
+++ /dev/null
@@ -1,287 +0,0 @@
-# coding=utf-8
-# Copyright 2022 x-plug and The HuggingFace Inc. team. All rights reserved.
-#
-# 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.
-""" MplugOwl model configuration """
-import copy
-import os
-from typing import Union
-
-from transformers.configuration_utils import PretrainedConfig
-from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
-from transformers.models.auto import CONFIG_MAPPING
-
-from loguru import logger
-
-MPLUG_OWL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
- "MAGAer13/mplug-owl-llama-7b": "https://huggingface.co/MAGAer13/mplug-owl-llama-7b/resolve/main/config.json",
- # See all MplugOwl models at https://huggingface.co/models?filter=mplug_owl
-}
-
-
-class MplugOwlVisionConfig(PretrainedConfig):
- r"""
- This is the configuration class to store the configuration of a [`MplugOwlVisionModel`]. It is used to instantiate a
- mPLUG-Owl vision encoder according to the specified arguments, defining the model architecture. Instantiating a
- configuration defaults will yield a similar configuration to that of the mPLUG-Owl
- [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b) architecture.
-
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
- documentation from [`PretrainedConfig`] for more information.
-
- Args:
- hidden_size (`int`, *optional*, defaults to 768):
- Dimensionality of the encoder layers and the pooler layer.
- intermediate_size (`int`, *optional*, defaults to 3072):
- Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
- num_hidden_layers (`int`, *optional*, defaults to 12):
- Number of hidden layers in the Transformer encoder.
- num_attention_heads (`int`, *optional*, defaults to 12):
- Number of attention heads for each attention layer in the Transformer encoder.
- image_size (`int`, *optional*, defaults to 224):
- The size (resolution) of each image.
- patch_size (`int`, *optional*, defaults to 32):
- The size (resolution) of each patch.
- hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
- The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
- `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
- layer_norm_eps (`float`, *optional*, defaults to 1e-5):
- The epsilon used by the layer normalization layers.
- attention_dropout (`float`, *optional*, defaults to 0.0):
- The dropout ratio for the attention probabilities.
- initializer_range (`float`, *optional*, defaults to 0.02):
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- initializer_factor (`float`, *optional*, defaults to 1):
- A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
- testing).
-
-
- ```"""
-
- model_type = "mplug_owl_vision_model"
-
- def __init__(
- self,
- hidden_size=1024,
- intermediate_size=4096,
- projection_dim=768,
- num_hidden_layers=24,
- num_attention_heads=16,
- num_channels=3,
- image_size=224,
- patch_size=14,
- hidden_act="quick_gelu",
- layer_norm_eps=1e-6,
- attention_dropout=0.0,
- initializer_range=0.02,
- initializer_factor=1.0,
- use_flash_attn=False,
- **kwargs,
- ):
- super().__init__(**kwargs)
- self.hidden_size = hidden_size
- self.intermediate_size = intermediate_size
- self.projection_dim = projection_dim
- self.num_hidden_layers = num_hidden_layers
- self.num_attention_heads = num_attention_heads
- self.num_channels = num_channels
- self.patch_size = patch_size
- self.image_size = image_size
- self.initializer_range = initializer_range
- self.initializer_factor = initializer_factor
- self.attention_dropout = attention_dropout
- self.layer_norm_eps = layer_norm_eps
- self.hidden_act = hidden_act
- self.use_flash_attn = use_flash_attn
-
- @classmethod
- def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
- config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
-
- # get the vision config dict if we are loading from MplugOwlConfig
- if config_dict.get("model_type") == "mplug-owl":
- config_dict = config_dict["vision_config"]
-
- if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
- logger.warning(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
-
- return cls.from_dict(config_dict, **kwargs)
-
-
-class MplugOwlVisualAbstractorConfig(PretrainedConfig):
- model_type = "mplug_owl_visual_abstract"
-
- def __init__(
- self,
- hidden_size=1024, #
- num_hidden_layers=6, #
- num_attention_heads=16, #
- intermediate_size=4096, #
- attention_probs_dropout_prob=0.1, #
- initializer_range=0.02,
- layer_norm_eps=1e-6, #
- encoder_hidden_size=1024, #
- **kwargs,
- ):
- super().__init__(**kwargs)
- self.hidden_size = hidden_size
- self.num_hidden_layers = num_hidden_layers
- self.num_attention_heads = num_attention_heads
- self.intermediate_size = intermediate_size
- self.attention_probs_dropout_prob = attention_probs_dropout_prob
- self.initializer_range = initializer_range
- self.layer_norm_eps = layer_norm_eps
- self.encoder_hidden_size = encoder_hidden_size
-
- @classmethod
- def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
- config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
-
- # get the visual_abstractor config dict if we are loading from MplugOwlConfig
- if config_dict.get("model_type") == "mplug-owl":
- config_dict = config_dict["abstractor_config"]
-
- if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
- logger.warning(f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")
-
- return cls.from_dict(config_dict, **kwargs)
-
-
-class MplugOwlConfig(PretrainedConfig):
- r"""
- [`MplugOwlConfig`] is the configuration class to store the configuration of a [`MplugOwlForConditionalGeneration`]. It is
- used to instantiate a mPLUG-Owl model according to the specified arguments, defining the vision model, Q-Former model
- and language model configs. Instantiating a configuration with the defaults will yield a similar configuration to
- that of the mPLUG-Owl [x-plug/x_plug-llama-7b](https://huggingface.co/x-plug/x_plug-llama-7b) architecture.
-
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
- documentation from [`PretrainedConfig`] for more information.
-
- Args:
- vision_config (`dict`, *optional*):
- Dictionary of configuration options used to initialize [`MplugOwlVisionConfig`].
- visual_abstractor_config (`dict`, *optional*):
- Dictionary of configuration options used to initialize [`MplugOwlVisualAbstractorConfig`].
- text_config (`dict`, *optional*):
- Dictionary of configuration options used to initialize any [`PretrainedConfig`].
- num_query_tokens (`int`, *optional*, defaults to 32):
- The number of query tokens passed through the Transformer.
-
- kwargs (*optional*):
- Dictionary of keyword arguments.
-
- Example:
-
- ```python
- >>> from transformers import (
- ... MplugOwlVisionConfig,
- ... MplugOwlVisualAbstractorConfig,
- ... OPTConfig,
- ... MplugOwlConfig,
- ... MplugOwlForConditionalGeneration,
- ... )
-
- >>> # Initializing a MplugOwlConfig with x-plug/x_plug-llama-7b style configuration
- >>> configuration = MplugOwlConfig()
-
- >>> # Initializing a MplugOwlForConditionalGeneration (with random weights) from the x-plug/x_plug-llama-7b style configuration
- >>> model = MplugOwlForConditionalGeneration(configuration)
-
- >>> # Accessing the model configuration
- >>> configuration = model.config
-
- >>> # We can also initialize a MplugOwlConfig from a MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig and any PretrainedConfig
-
- >>> # Initializing mPLUG-Owl vision, mPLUG-Owl Q-Former and language model configurations
- >>> vision_config = MplugOwlVisionConfig()
- >>> visual_abstractor_config = MplugOwlVisualAbstractorConfig()
- >>> text_config = OPTConfig()
-
- >>> config = MplugOwlConfig.from_text_vision_configs(vision_config, visual_abstractor_config, text_config)
- ```"""
-
- model_type = "mplug-owl"
- is_composition = True
-
- def __init__(self, vision_config=None, visual_abstractor_config=None, text_config=None, num_query_tokens=64, **kwargs):
- super().__init__(**kwargs)
- if vision_config is None:
- vision_config = MplugOwlVisionConfig().to_dict()
- logger.info("vision_config is None.")
-
- if visual_abstractor_config is None:
- visual_abstractor_config = {}
- logger.info("abstractor_config is None. ")
-
- if text_config is None:
- # we use LLAMA 7b by default
- from ..llama.configuration_llama import LlamaConfig
-
- text_config = LlamaConfig(pad_token_id=2).to_dict()
- logger.info("text_config is None.")
-
- self.vision_config = MplugOwlVisionConfig(**vision_config)
- self.visual_abstractor_config = MplugOwlVisualAbstractorConfig(**visual_abstractor_config)
- # self.visual_abstractor_config.layer_norm_eps = 1e-6
- text_model_type = text_config["model_type"] if "model_type" in text_config else "llama"
- self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
-
- self.tie_word_embeddings = self.text_config.tie_word_embeddings
- self.is_encoder_decoder = self.text_config.is_encoder_decoder
-
- self.num_query_tokens = num_query_tokens
- # self.visual_abstractor_config.encoder_hidden_size = self.vision_config.hidden_size
- self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
- self.initializer_factor = 1.0
- self.initializer_range = 0.02
-
- for attr in dir(self.text_config):
- if not hasattr(self, attr):
- setattr(self, attr, getattr(self.text_config, attr))
-
- @classmethod
- def from_vision_visual_abstractor_text_configs(
- cls,
- vision_config: MplugOwlVisionConfig,
- visual_abstractor_config: MplugOwlVisualAbstractorConfig,
- text_config: PretrainedConfig,
- **kwargs,
- ):
- r"""
- Instantiate a [`MplugOwlConfig`] (or a derived class) from a mPLUG-Owl vision model, Q-Former and language model
- configurations.
-
- Returns:
- [`MplugOwlConfig`]: An instance of a configuration object
- """
-
- return cls(
- vision_config=vision_config.to_dict(),
- visual_abstractor_config=visual_abstractor_config.to_dict(),
- text_config=text_config.to_dict(),
- **kwargs,
- )
-
- def to_dict(self):
- """
- Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
-
- Returns:
- `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
- """
- output = copy.deepcopy(self.__dict__)
- output["vision_config"] = self.vision_config.to_dict()
- output["visual_abstractor_config"] = self.visual_abstractor_config.to_dict()
- output["text_config"] = self.text_config.to_dict()
- output["model_type"] = self.__class__.model_type
- return output
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/modeling_mplug_owl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/modeling_mplug_owl.py
deleted file mode 100644
index 07bf9f0cc86e1f5bc7a87ea866d8fa84233bddae..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/modeling_mplug_owl.py
+++ /dev/null
@@ -1,1838 +0,0 @@
-# coding=utf-8
-# Copyright 2022 x-plug The HuggingFace Inc. team. All rights reserved.
-#
-# 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.
-""" PyTorch MplugOwl model. """
-
-import math
-from typing import Any, Optional, Tuple, Union
-from loguru import logger
-
-try:
- from flash_attn.flash_attn_interface import flash_attn_unpadded_func
-
- flash_attn_func = flash_attn_unpadded_func
-except:
- flash_attn_func = None
- logger.warning("Error importing flash_attn in mplug_owl. Please install flash-attn first.")
-
-import math
-from dataclasses import dataclass
-from typing import Any, Optional, Tuple, Union
-
-import torch
-import torch.utils.checkpoint
-from torch import nn
-import einops
-
-from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, BaseModelOutputWithPastAndCrossAttentions
-from transformers.modeling_utils import PreTrainedModel
-from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
-from transformers.utils import (
- ModelOutput,
- add_start_docstrings,
- add_start_docstrings_to_model_forward,
- replace_return_docstrings,
-)
-from transformers.models.auto import AutoModelForCausalLM
-from .configuration_mplug_owl import MplugOwlConfig, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig
-
-_CHECKPOINT_FOR_DOC = "MAGAer13/mplug-owl-llama-7b"
-_CONFIG_FOR_DOC = "MplugOwlConfig"
-
-
-MPLUG_OWL_PRETRAINED_MODEL_ARCHIVE_LIST = [
- "MAGAer13/mplug-owl-llama-7b",
- # See all MplugOwl models at https://huggingface.co/models?filter=mplug_owl
-]
-
-
-@dataclass
-class MplugOwlForConditionalGenerationModelOutput(ModelOutput):
- """
- Class defining the outputs of [`MPlugOwlForConditionalGeneration`].
-
- Args:
- loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
- Language modeling loss from the language model.
- logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
- Prediction scores of the language modeling head of the language model.
- vision_outputs (`BaseModelOutputWithPooling`):
- Outputs of the vision encoder.
-
- language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`):
- Outputs of the language model.
- """
-
- loss: Optional[Tuple[torch.FloatTensor]] = None
- logits: Optional[Tuple[torch.FloatTensor]] = None
- vision_outputs: Optional[torch.FloatTensor] = None
- language_model_outputs: Optional[Tuple[torch.FloatTensor]] = None
-
- def to_tuple(self) -> Tuple[Any]:
- return tuple(self[k] if k not in ["vision_outputs", "language_model_outputs"] else getattr(self, k).to_tuple() for k in self.keys())
-
-
-def get_ltor_masks_and_position_ids_from_embeddings(data):
- """Build masks and position id for left to right model."""
-
- # Extract batch size and sequence length.
- micro_batch_size, seq_length = data.size()[:2]
-
- # Attention mask (lower triangular).
- att_mask_batch = 1
- attention_mask = torch.tril(torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)).view(att_mask_batch, 1, seq_length, seq_length)
-
- # Loss mask.
- loss_mask = torch.ones(data.size()[:2], dtype=torch.float, device=data.device)
-
- # Position ids.
- position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
- position_ids = position_ids.unsqueeze(0).expand_as(data[..., 0])
-
- # Convert attention mask to binary:
- attention_mask = attention_mask < 0.5
-
- return attention_mask, loss_mask, position_ids
-
-
-class MplugOwlVisionEmbeddings(nn.Module):
- def __init__(self, config: MplugOwlVisionConfig):
- super().__init__()
- self.config = config
- self.hidden_size = config.hidden_size
- self.image_size = config.image_size
- self.patch_size = config.patch_size
-
- self.cls_token = nn.Parameter(torch.randn(1, 1, self.hidden_size))
-
- self.patch_embed = nn.Conv2d(
- in_channels=3,
- out_channels=self.hidden_size,
- kernel_size=self.patch_size,
- stride=self.patch_size,
- bias=False,
- )
-
- self.num_patches = (self.image_size // self.patch_size) ** 2
-
- self.position_embedding = nn.Parameter(torch.randn(1, self.num_patches + 1, self.hidden_size))
-
- self.pre_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps)
-
- def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
- # [B, C, T, H, W] or [B, C, H, W]
- batch_size = pixel_values.size(0)
- T = pixel_values.size(2) if pixel_values.dim() > 4 else 1
- if T > 1:
- pixel_values = einops.rearrange(pixel_values, "b c t h w -> (b t) c h w")
- image_embeds = self.patch_embed(pixel_values)
- image_embeds = image_embeds.flatten(2).transpose(1, 2)
-
- class_embeds = self.cls_token.expand(batch_size * T, 1, -1).to(image_embeds.dtype)
- embeddings = torch.cat([class_embeds, image_embeds], dim=1)
- embeddings = embeddings + self.position_embedding[:, : embeddings.size(1)].to(image_embeds.dtype)
- embeddings = self.pre_layernorm(embeddings)
- embeddings = einops.rearrange(embeddings, "(b t) n d -> b t n d", b=batch_size)
- return embeddings
-
-
-class LayerNormFp32(nn.LayerNorm):
- """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- def forward(self, x: torch.Tensor):
- output = torch.nn.functional.layer_norm(
- x.float(),
- self.normalized_shape,
- self.weight.float() if self.weight is not None else None,
- self.bias.float() if self.bias is not None else None,
- self.eps,
- )
- return output.type_as(x)
-
-
-class QuickGELU(nn.Module):
- def forward(self, x: torch.Tensor):
- return x * torch.sigmoid(1.702 * x)
-
-
-class MplugOwlVisionLocalTemporal(nn.Module):
- def __init__(self, config):
- super(MplugOwlVisionLocalTemporal, self).__init__()
-
- self.image_size = config.image_size
- self.patch_size = config.patch_size
- self.num_patches = 1 + (self.image_size // self.patch_size) ** 2
- self.hidden_size = config.hidden_size
- d_bottleneck = self.hidden_size // 2
-
- self.ln = LayerNormFp32(self.hidden_size)
- self.down_proj = nn.Conv3d(self.hidden_size, d_bottleneck, kernel_size=1, stride=1, padding=0)
- self.conv = nn.Conv3d(d_bottleneck, d_bottleneck, kernel_size=(3, 1, 1), stride=1, padding=(1, 0, 0), groups=d_bottleneck)
- self.up_proj = nn.Conv3d(d_bottleneck, self.hidden_size, kernel_size=1, stride=1, padding=0)
-
- nn.init.constant_(self.up_proj.weight, 0)
- nn.init.constant_(self.up_proj.bias, 0)
-
- self.activation_func = QuickGELU()
-
- def forward(self, x):
- # [b, t, s, c]
- T = x.size(1)
- H = int((self.num_patches - 1) ** 0.5)
- cls_token, x = x[:, :, 0:1], x[:, :, 1:]
- x = self.ln(x)
- x = einops.rearrange(x, "b t (h w) c -> b c t h w", h=H)
- x = self.down_proj(x)
- if self.conv.weight.dtype == torch.bfloat16:
- x = torch.nn.functional.conv3d(x.half(), self.conv.weight.half(), bias=self.conv.bias.half(), stride=1, padding=(1, 0, 0), groups=self.conv.weight.shape[0]).to(cls_token.dtype)
- else:
- x = self.conv(x)
- x = self.activation_func(x)
- x = self.up_proj(x)
- x = einops.rearrange(x, "b c t h w -> b t (h w) c")
- x = torch.cat([cls_token, x], dim=2)
- return x
-
-
-class MplugOwlVisionAttention(nn.Module):
- """Multi-headed attention from 'Attention Is All You Need' paper"""
-
- def __init__(self, config):
- super().__init__()
- self.config = config
- self.hidden_size = config.hidden_size
- self.num_heads = config.num_attention_heads
- self.head_dim = self.hidden_size // self.num_heads
- if self.head_dim * self.num_heads != self.hidden_size:
- raise ValueError(f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:" f" {self.num_heads}).")
- self.scale = self.head_dim**-0.5
- self.dropout = nn.Dropout(config.attention_dropout)
-
- self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size)
- self.dense = nn.Linear(self.hidden_size, self.hidden_size)
-
- def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- head_mask: Optional[torch.Tensor] = None,
- output_attentions: Optional[bool] = False,
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
- """Input shape: Batch x Time x Channel"""
-
- bsz, seq_len, embed_dim = hidden_states.size()
-
- mixed_qkv = self.query_key_value(hidden_states)
-
- mixed_qkv = mixed_qkv.reshape(bsz, seq_len, self.num_heads, 3, embed_dim // self.num_heads).permute(3, 0, 2, 1, 4) # [3, b, np, sq, hn]
- query_states, key_states, value_states = (
- mixed_qkv[0],
- mixed_qkv[1],
- mixed_qkv[2],
- )
- # if self.config.use_flash_attn and flash_attn_func is not None:
- if False:
- # [b*sq, np, hn]
- query_states = query_states.permute(0, 2, 1, 3).contiguous()
- query_states = query_states.view(query_states.size(0) * query_states.size(1), query_states.size(2), -1)
-
- key_states = key_states.permute(0, 2, 1, 3).contiguous()
- key_states = key_states.view(key_states.size(0) * key_states.size(1), key_states.size(2), -1)
-
- value_states = value_states.permute(0, 2, 1, 3).contiguous()
- value_states = value_states.view(value_states.size(0) * value_states.size(1), value_states.size(2), -1)
-
- cu_seqlens = torch.arange(0, (bsz + 1) * seq_len, step=seq_len, dtype=torch.int32, device=query_states.device)
-
- context_layer = flash_attn_func(
- query_states,
- key_states,
- value_states,
- cu_seqlens,
- cu_seqlens,
- seq_len,
- seq_len,
- self.dropout if self.training else 0.0,
- softmax_scale=self.scale,
- causal=False,
- return_attn_probs=False,
- )
- # [b*sq, np, hn] => [b, sq, np, hn]
- context_layer = context_layer.view(bsz, seq_len, context_layer.size(1), context_layer.size(2))
- else:
- # Take the dot product between "query" and "key" to get the raw attention scores.
- attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
-
- attention_scores = attention_scores * self.scale
-
- # Normalize the attention scores to probabilities.
- attention_probs = torch.softmax(attention_scores, dim=-1)
-
- # This is actually dropping out entire tokens to attend to, which might
- # seem a bit unusual, but is taken from the original Transformer paper.
- attention_probs = self.dropout(attention_probs)
-
- # Mask heads if we want to
- if head_mask is not None:
- attention_probs = attention_probs * head_mask
-
- context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
-
- new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size,)
- context_layer = context_layer.reshape(new_context_layer_shape)
-
- output = self.dense(context_layer)
-
- outputs = (output, attention_probs) if output_attentions else (output, None)
-
- return outputs
-
-
-class MplugOwlMLP(nn.Module):
- def __init__(self, config):
- super().__init__()
- self.config = config
- self.activation_fn = QuickGELU()
- self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
- self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- hidden_states = self.fc1(hidden_states)
- hidden_states = self.activation_fn(hidden_states)
- hidden_states = self.fc2(hidden_states)
- return hidden_states
-
-
-class MplugOwlVisionEncoderLayer(nn.Module):
- def __init__(self, config: MplugOwlVisionConfig):
- super().__init__()
- self.hidden_size = config.hidden_size
- self.temporal = MplugOwlVisionLocalTemporal(config)
- self.self_attn = MplugOwlVisionAttention(config)
- self.input_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps)
- self.mlp = MplugOwlMLP(config)
- self.post_attention_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: torch.Tensor,
- output_attentions: Optional[bool] = False,
- ) -> Tuple[torch.FloatTensor]:
- """
- Args:
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, time, seq_len, embed_dim)`
- attention_mask (`torch.FloatTensor`): attention mask of size
- `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
- `(config.encoder_attention_heads,)`.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- """
- B, T = hidden_states.size(0), hidden_states.size(1)
- if T > 1:
- hidden_states = hidden_states + self.temporal(hidden_states)
- hidden_states = einops.rearrange(hidden_states, "b t n d -> (b t) n d")
-
- residual = hidden_states
-
- hidden_states = self.input_layernorm(hidden_states)
- hidden_states, attn_weights = self.self_attn(
- hidden_states=hidden_states,
- head_mask=attention_mask,
- output_attentions=output_attentions,
- )
- hidden_states = hidden_states + residual
- residual = hidden_states
- hidden_states = self.post_attention_layernorm(hidden_states)
- hidden_states = self.mlp(hidden_states)
-
- hidden_states = hidden_states + residual
- hidden_states = einops.rearrange(hidden_states, "(b t) n d -> b t n d", b=B)
-
- outputs = (hidden_states,)
-
- if output_attentions:
- outputs += (attn_weights,)
-
- return outputs
-
-
-class MplugOwlPreTrainedModel(PreTrainedModel):
- """
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
- models.
- """
-
- config_class = MplugOwlConfig
- base_model_prefix = "mplug_owl"
- supports_gradient_checkpointing = True
- _keys_to_ignore_on_load_missing = [
- r"position_ids",
- r"language_model.encoder.embed_tokens.weight",
- r"language_model.decoder.embed_tokens.weight",
- r"language_model.lm_head.weight",
- ]
- _no_split_modules = [
- "MplugOwlVisionEncoderLayer",
- "LlamaDecoderLayer",
- "MplugOwlVisualAbstractorLayer",
- "LlamaForCausalLM",
- "Parameter",
- ]
- _keep_in_fp32_modules = ["wo"]
-
- def _init_weights(self, module):
- """Initialize the weights"""
- factor = self.config.initializer_range
- if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
- module.weight.data.normal_(mean=0.0, std=factor)
- if hasattr(module, "bias") and module.bias is not None:
- module.bias.data.zero_()
-
- if isinstance(module, MplugOwlVisionEmbeddings):
- if hasattr(self.config, "vision_config"):
- factor = self.config.vision_config.initializer_range
- nn.init.trunc_normal_(module.position_embedding, mean=0.0, std=factor)
- nn.init.trunc_normal_(module.cls_token, mean=0.0, std=factor)
-
- elif isinstance(module, nn.LayerNorm):
- module.bias.data.zero_()
- module.weight.data.fill_(1.0)
- elif isinstance(module, nn.Linear) and module.bias is not None:
- module.bias.data.zero_()
- elif isinstance(module, nn.Parameter):
- raise ValueError
- nn.init.trunc_normal_(module.data, mean=0.0, std=factor)
-
- def _set_gradient_checkpointing(self, module, value=False):
- if isinstance(module, MplugOwlVisionEncoder):
- module.gradient_checkpointing = value
-
-
-MPLUG_OWL_START_DOCSTRING = r"""
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
- etc.)
-
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
- and behavior.
-
- Parameters:
- config ([`MplugOwlConfig`]): Model configuration class with all the parameters of the model.
- Initializing with a config file does not load the weights associated with the model, only the
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
-"""
-
-MPLUG_OWL_VISION_INPUTS_DOCSTRING = r"""
- Args:
- pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
- Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for
- details.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
- tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
- more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-"""
-
-MPLUG_OWL_TEXT_INPUTS_DOCSTRING = r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
- it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- [What are attention masks?](../glossary#attention-mask)
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are decoder input IDs?](../glossary#decoder-input-ids)
-
- T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
- is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
-
- To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
- Training](./t5#training).
- decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
- tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
- more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-"""
-
-MPLUG_OWL_INPUTS_DOCSTRING = r"""
- Args:
- pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
- Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for
- details.
-
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be
- provided to serve as text prompt, which the language model can continue.
-
- Indices can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
-
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an
- encoder-decoder language model (like T5) is used.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids)
-
- decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
-
- Only relevant in case an encoder-decoder language model (like T5) is used.
-
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
- tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
- more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-"""
-
-
-class MplugOwlVisionEncoder(nn.Module):
- """
- Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
- [`MplugOwlVisionEncoderLayer`].
-
- Args:
- config (`MplugOwlVisionConfig`):
- The corresponding vision configuration for the `MplugOwlEncoder`.
- """
-
- def __init__(self, config: MplugOwlVisionConfig):
- super().__init__()
- self.config = config
- self.layers = nn.ModuleList([MplugOwlVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
- self.gradient_checkpointing = False
-
- def forward(
- self,
- inputs_embeds,
- attention_mask: Optional[torch.Tensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, BaseModelOutput]:
- r"""
- Args:
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
- Embedded representation of the inputs. Should be float, not int tokens.
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- encoder_states = () if output_hidden_states else None
- all_attentions = () if output_attentions else None
-
- hidden_states = inputs_embeds
- for idx, encoder_layer in enumerate(self.layers):
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
- if self.gradient_checkpointing and self.training:
-
- def create_custom_forward(module):
- def custom_forward(*inputs):
- return module(*inputs, output_attentions)
-
- return custom_forward
-
- layer_outputs = torch.utils.checkpoint.checkpoint(
- create_custom_forward(encoder_layer),
- hidden_states,
- attention_mask,
- )
- else:
- layer_outputs = encoder_layer(
- hidden_states,
- attention_mask,
- output_attentions=output_attentions,
- )
-
- hidden_states = layer_outputs[0]
-
- if output_attentions:
- all_attentions = all_attentions + (layer_outputs[1],)
-
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
-
- if not return_dict:
- return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
- return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
-
-
-class MplugOwlVisionModel(MplugOwlPreTrainedModel):
- main_input_name = "pixel_values"
- config_class = MplugOwlVisionConfig
-
- def __init__(self, config: MplugOwlVisionConfig):
- super().__init__(config)
- self.config = config
- self.hidden_size = config.hidden_size
-
- self.embeddings = MplugOwlVisionEmbeddings(config)
- self.encoder = MplugOwlVisionEncoder(config)
- self.post_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps)
-
- self.post_init()
-
- @add_start_docstrings_to_model_forward(MPLUG_OWL_VISION_INPUTS_DOCSTRING)
- @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=MplugOwlVisionConfig)
- def forward(
- self,
- pixel_values: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, BaseModelOutputWithPooling]:
- r"""
- Returns:
-
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- if pixel_values is None:
- raise ValueError("You have to specify pixel_values")
-
- hidden_states = self.embeddings(pixel_values) # [B, T, N, D]
-
- encoder_outputs = self.encoder(
- inputs_embeds=hidden_states,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- last_hidden_state = encoder_outputs[0]
- last_hidden_state = self.post_layernorm(last_hidden_state)
-
- pooled_output = last_hidden_state[:, :, 0, :].mean(1)
- pooled_output = self.post_layernorm(pooled_output)
-
- if not return_dict:
- return (last_hidden_state, pooled_output) + encoder_outputs[1:]
-
- return BaseModelOutputWithPooling(
- last_hidden_state=last_hidden_state,
- pooler_output=pooled_output,
- hidden_states=encoder_outputs.hidden_states,
- attentions=encoder_outputs.attentions,
- )
-
- def get_input_embeddings(self):
- return self.embeddings
-
-
-class MplugOwlVisualAbstractorMLP(nn.Module):
- def __init__(self, config: MplugOwlVisualAbstractorConfig):
- super().__init__()
- self.config = config
- in_features = config.hidden_size
- hidden_features = config.intermediate_size
- if hidden_features != 2816:
- hidden_features = int(2 * hidden_features / 3)
- multiple_of = 256
- hidden_features = multiple_of * ((hidden_features + multiple_of - 1) // multiple_of)
- self.act = nn.SiLU()
-
- self.w1 = nn.Linear(in_features, hidden_features)
- self.w2 = nn.Linear(hidden_features, in_features)
- self.w3 = nn.Linear(in_features, hidden_features)
- self.ffn_ln = LayerNormFp32(hidden_features, eps=config.layer_norm_eps)
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- hidden_states = self.act(self.w1(hidden_states)) * self.w3(hidden_states)
- hidden_states = self.ffn_ln(hidden_states)
- hidden_states = self.w2(hidden_states)
- return hidden_states
-
-
-class MplugOwlVisualAbstractorMultiHeadAttention(nn.Module):
- def __init__(self, config: MplugOwlVisualAbstractorConfig):
- super().__init__()
- self.config = config
- if config.hidden_size % config.num_attention_heads != 0:
- raise ValueError("The hidden size (%d) is not a multiple of the number of attention heads (%d)" % (config.hidden_size, config.num_attention_heads))
-
- self.num_attention_heads = config.num_attention_heads
- self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
- self.all_head_size = self.num_attention_heads * self.attention_head_size
-
- self.query = nn.Linear(config.hidden_size, self.all_head_size)
- self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
- self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
-
- self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
- self.save_attention = False
-
- def save_attn_gradients(self, attn_gradients):
- self.attn_gradients = attn_gradients
-
- def get_attn_gradients(self):
- return self.attn_gradients
-
- def save_attention_map(self, attention_map):
- self.attention_map = attention_map
-
- def get_attention_map(self):
- return self.attention_map
-
- def transpose_for_scores(self, x):
- new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
- x = x.view(*new_x_shape)
- return x.permute(0, 2, 1, 3)
-
- def forward(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- encoder_hidden_states=None,
- encoder_attention_mask=None,
- past_key_value=None,
- output_attentions=False,
- ):
- # If this is instantiated as a cross-attention module, the keys
- # and values come from an encoder; the attention mask needs to be
- # such that the encoder's padding tokens are not attended to.
- key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
- value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
- attention_mask = encoder_attention_mask
-
- mixed_query_layer = self.query(hidden_states)
-
- query_layer = self.transpose_for_scores(mixed_query_layer)
-
- past_key_value = (key_layer, value_layer)
-
- # Take the dot product between "query" and "key" to get the raw attention scores.
- attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
-
- attention_scores = attention_scores / math.sqrt(self.attention_head_size)
-
- if attention_mask is not None:
- # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
- attention_scores = attention_scores + attention_mask
-
- # Normalize the attention scores to probabilities.
- attention_probs = nn.Softmax(dim=-1)(attention_scores)
-
- if self.save_attention:
- self.save_attention_map(attention_probs)
- attention_probs.register_hook(self.save_attn_gradients)
-
- # This is actually dropping out entire tokens to attend to, which might
- # seem a bit unusual, but is taken from the original Transformer paper.
- attention_probs_dropped = self.dropout(attention_probs)
-
- # Mask heads if we want to
- if head_mask is not None:
- attention_probs_dropped = attention_probs_dropped * head_mask
-
- context_layer = torch.matmul(attention_probs_dropped, value_layer)
-
- context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
- new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
- context_layer = context_layer.view(*new_context_layer_shape)
-
- outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
-
- outputs = outputs + (past_key_value,)
- return outputs
-
-
-class MplugOwlVisualAbstractorCrossOutput(nn.Module):
- def __init__(self, config: MplugOwlVisualAbstractorConfig):
- super().__init__()
- dim = config.hidden_size
- self.out_proj = nn.Linear(dim, dim, bias=True)
- self.norm2 = LayerNormFp32(dim)
- self.mlp = MplugOwlVisualAbstractorMLP(config)
-
- def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
- input_tensor = input_tensor + self.out_proj(hidden_states)
- input_tensor = input_tensor + self.mlp(self.norm2(input_tensor))
- return input_tensor
-
-
-class MplugOwlVisualAbstractorAttention(nn.Module):
- def __init__(self, config: MplugOwlVisualAbstractorConfig):
- super().__init__()
- self.attention = MplugOwlVisualAbstractorMultiHeadAttention(config)
- self.output = MplugOwlVisualAbstractorCrossOutput(config)
- self.pruned_heads = set()
- self.norm1 = LayerNormFp32(config.hidden_size)
- self.normk = LayerNormFp32(config.hidden_size)
-
- def prune_heads(self, heads):
- if len(heads) == 0:
- return
- heads, index = find_pruneable_heads_and_indices(heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads)
-
- # Prune linear layers
- self.attention.query = prune_linear_layer(self.attention.query, index)
- self.attention.key = prune_linear_layer(self.attention.key, index)
- self.attention.value = prune_linear_layer(self.attention.value, index)
- self.output.dense = prune_linear_layer(self.output.out_proj, index, dim=1)
-
- # Update hyper params and store pruned heads
- self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
- self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
- self.pruned_heads = self.pruned_heads.union(heads)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.FloatTensor] = None,
- head_mask: Optional[torch.FloatTensor] = None,
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
- past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
- output_attentions: Optional[bool] = False,
- ) -> Tuple[torch.Tensor]:
- # HACK we apply norm on q and k
- hidden_states = self.norm1(hidden_states)
- encoder_hidden_states = self.normk(encoder_hidden_states)
- encoder_hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
- encoder_attention_mask = torch.cat([attention_mask, encoder_attention_mask], dim=-1)
- self_outputs = self.attention(
- hidden_states,
- attention_mask,
- head_mask,
- encoder_hidden_states,
- encoder_attention_mask,
- past_key_value,
- output_attentions,
- )
- attention_output = self.output(self_outputs[0], hidden_states)
- # add attentions if we output them
- outputs = (attention_output,) + self_outputs[1:]
- return outputs
-
-
-class MplugOwlVisualAbstractorLayer(nn.Module):
- def __init__(self, config, layer_idx):
- super().__init__()
- self.chunk_size_feed_forward = config.chunk_size_feed_forward
- self.seq_len_dim = 1
-
- self.layer_idx = layer_idx
-
- self.crossattention = MplugOwlVisualAbstractorAttention(config)
- self.has_cross_attention = True
-
- def forward(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- encoder_hidden_states=None,
- encoder_attention_mask=None,
- output_attentions=False,
- ):
- if encoder_hidden_states is None:
- raise ValueError("encoder_hidden_states must be given for cross-attention layers")
- cross_attention_outputs = self.crossattention(
- hidden_states,
- attention_mask,
- head_mask,
- encoder_hidden_states,
- encoder_attention_mask,
- output_attentions=output_attentions,
- )
- query_attention_output = cross_attention_outputs[0]
-
- outputs = (query_attention_output,)
- return outputs
-
-
-class MplugOwlVisualAbstractorEncoder(nn.Module):
- def __init__(self, config):
- super().__init__()
- self.config = config
- self.layers = nn.ModuleList([MplugOwlVisualAbstractorLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
- self.gradient_checkpointing = False
-
- def forward(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- encoder_hidden_states=None,
- encoder_attention_mask=None,
- past_key_values=None,
- output_attentions=False,
- output_hidden_states=False,
- return_dict=True,
- ):
- all_hidden_states = () if output_hidden_states else None
-
- for i in range(self.config.num_hidden_layers):
- layer_module = self.layers[i]
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- layer_head_mask = head_mask[i] if head_mask is not None else None
- past_key_value = past_key_values[i] if past_key_values is not None else None
-
- if getattr(self.config, "gradient_checkpointing", False) and self.training:
-
- def create_custom_forward(module):
- def custom_forward(*inputs):
- return module(*inputs, past_key_value, output_attentions)
-
- return custom_forward
-
- layer_outputs = torch.utils.checkpoint.checkpoint(
- create_custom_forward(layer_module),
- hidden_states,
- attention_mask,
- layer_head_mask,
- encoder_hidden_states,
- encoder_attention_mask,
- )
- else:
- layer_outputs = layer_module(
- hidden_states,
- attention_mask,
- layer_head_mask,
- encoder_hidden_states,
- encoder_attention_mask,
- output_attentions,
- )
-
- hidden_states = layer_outputs[0]
-
- return BaseModelOutput(
- last_hidden_state=hidden_states,
- )
-
-
-class MplugOwlVisualAbstractorModel(MplugOwlPreTrainedModel):
- def __init__(self, config: MplugOwlVisualAbstractorConfig, language_hidden_size):
- super().__init__(config)
- self.config = config
-
- self.encoder = MplugOwlVisualAbstractorEncoder(config)
- self.visual_fc = torch.nn.Linear(config.hidden_size, language_hidden_size)
- self.temporal_visual_fc = torch.nn.Linear(config.hidden_size, language_hidden_size)
- self.vit_eos = torch.nn.Parameter(torch.randn(1, 1, language_hidden_size))
- nn.init.trunc_normal_(self.vit_eos, mean=0.0, std=self.config.initializer_range)
- self.post_init()
-
- def _prune_heads(self, heads_to_prune):
- """
- Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
- class PreTrainedModel
- """
- for layer, heads in heads_to_prune.items():
- self.encoder.layer[layer].attention.prune_heads(heads)
-
- def get_extended_attention_mask(
- self,
- attention_mask: torch.Tensor,
- input_shape: Tuple[int],
- device: torch.device,
- ) -> torch.Tensor:
- """
- Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
-
- Arguments:
- attention_mask (`torch.Tensor`):
- Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
- input_shape (`Tuple[int]`):
- The shape of the input to the model.
- device: (`torch.device`):
- The device of the input to the model.
-
- Returns:
- `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
- """
- # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
- # ourselves in which case we just need to make it broadcastable to all heads.
- if attention_mask.dim() == 3:
- extended_attention_mask = attention_mask[:, None, :, :]
- elif attention_mask.dim() == 2:
- # Provided a padding mask of dimensions [batch_size, seq_length]
- # - the model is an encoder, so make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
- extended_attention_mask = attention_mask[:, None, None, :]
- else:
- raise ValueError("Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(input_shape, attention_mask.shape))
-
- # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
- # masked positions, this operation will create a tensor which is 0.0 for
- # positions we want to attend and -10000.0 for masked positions.
- # Since we are adding it to the raw scores before the softmax, this is
- # effectively the same as removing these entirely.
- extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
- extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
- return extended_attention_mask
-
- def forward(
- self,
- query_embeds,
- temporal_query_embeds=None,
- attention_mask=None,
- head_mask=None,
- encoder_hidden_states=None,
- encoder_attention_mask=None,
- past_key_values=None,
- output_attentions=None,
- output_hidden_states=None,
- return_dict=None,
- ):
- r"""
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, `optional`):
- Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
- the model is configured as a decoder.
- encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`):
- Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
- the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of:
- shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): Contains precomputed key and
- value hidden states of the attention blocks. Can be used to speed up decoding. If `past_key_values` are
- used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key
- value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape
- `(batch_size, sequence_length)`.
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- T = encoder_hidden_states.size(1)
- if T == 1 or temporal_query_embeds is None:
- embedding_output = query_embeds
- else:
- embedding_output = torch.cat([query_embeds, temporal_query_embeds], dim=1)
- input_shape = embedding_output.size()[:-1]
- batch_size, seq_length = input_shape
- device = embedding_output.device
-
- encoder_hidden_states = einops.rearrange(encoder_hidden_states, "b t n d -> b (t n) d")
-
- # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
- # ourselves in which case we just need to make it broadcastable to all heads.
- if attention_mask is None:
- attention_mask = torch.ones((embedding_output.shape[0], embedding_output.shape[1]), dtype=torch.long, device=embedding_output.device)
- extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device)
-
- # If a 2D or 3D attention mask is provided for the cross-attention
- # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
- if encoder_hidden_states is not None:
- if type(encoder_hidden_states) == list:
- encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
- else:
- (
- encoder_batch_size,
- encoder_sequence_length,
- _,
- ) = encoder_hidden_states.size()
- encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
-
- if type(encoder_attention_mask) == list:
- encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
- elif encoder_attention_mask is None:
- encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
- encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
- else:
- encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
- else:
- encoder_extended_attention_mask = None
-
- # Prepare head mask if needed
- # 1.0 in head_mask indicate we keep the head
- # attention_probs has shape bsz x n_heads x N x N
- # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
- # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
- head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
-
- encoder_outputs = self.encoder(
- embedding_output,
- attention_mask=extended_attention_mask,
- head_mask=head_mask,
- encoder_hidden_states=encoder_hidden_states,
- encoder_attention_mask=encoder_extended_attention_mask,
- past_key_values=past_key_values,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- sequence_output = encoder_outputs[0]
- pooled_output = sequence_output[:, 0, :]
-
- if T == 1 or temporal_query_embeds is None:
- temporal_sequence_output = None
- else:
- temporal_sequence_output = sequence_output[:, query_embeds.size(1) :]
- sequence_output = sequence_output[:, : query_embeds.size(1)]
-
- sequence_output = self.visual_fc(sequence_output)
- if temporal_sequence_output is not None:
- sequence_output += self.temporal_visual_fc(temporal_sequence_output)
- sequence_output = torch.cat([sequence_output, self.vit_eos.repeat(sequence_output.shape[0], 1, 1)], dim=1)
-
- return BaseModelOutputWithPooling(
- last_hidden_state=sequence_output,
- pooler_output=pooled_output,
- hidden_states=encoder_outputs.hidden_states,
- )
-
-
-@add_start_docstrings(
- """
- mPLUG-Owl Model for generating text and image features. The model consists of a vision encoder, Querying Transformer
- (Q-Former) and a language model.
- """,
- MPLUG_OWL_START_DOCSTRING,
-)
-class MplugOwlModel(MplugOwlPreTrainedModel):
- config_class = MplugOwlConfig
- main_input_name = "pixel_values"
-
- def __init__(self, config: MplugOwlConfig, *inputs, **kwargs):
- super().__init__(config, *inputs, **kwargs)
-
- self.vision_model = MplugOwlVisionModel(config.vision_config)
-
- self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size))
- self.temporal_query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size))
- self.abstractor = MplugOwlVisualAbstractorModel(config.visual_abstractor_config, config.text_config.hidden_size)
-
- # if config.use_decoder_only_language_model:
- # from llama.modeling_llama import LlamaForCausalLM
- language_model = AutoModelForCausalLM.from_config(config.text_config)
- # else:
- # language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
- self.language_model = language_model
-
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_input_embeddings(self):
- return self.language_model.get_input_embeddings()
-
- def set_input_embeddings(self, value):
- self.language_model.set_input_embeddings(value)
-
- def set_output_embeddings(self, new_embeddings):
- self.language_model.set_output_embeddings(new_embeddings)
-
- def get_output_embeddings(self) -> nn.Module:
- return self.language_model.get_output_embeddings()
-
- def get_encoder(self):
- return self.language_model.get_encoder()
-
- def get_decoder(self):
- return self.language_model.get_decoder()
-
- def _tie_weights(self):
- if not self.config.use_decoder_only_language_model:
- self.language_model.encoder.embed_tokens = self.language_model.shared
- self.language_model.decoder.embed_tokens = self.language_model.shared
-
- def get_text_features(
- self,
- input_ids: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- decoder_input_ids: Optional[torch.Tensor] = None,
- decoder_attention_mask: Optional[torch.Tensor] = None,
- labels: Optional[torch.Tensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ):
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- if self.config.use_decoder_only_language_model:
- text_outputs = self.language_model(
- input_ids=input_ids,
- attention_mask=attention_mask,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- else:
- inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
-
- text_outputs = self.language_model(
- inputs_embeds=inputs_embeds,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- decoder_attention_mask=decoder_attention_mask,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- labels=labels,
- )
-
- return text_outputs
-
- def get_image_features(
- self,
- pixel_values: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ):
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- vision_outputs = self.vision_model(
- pixel_values=pixel_values,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- return vision_outputs
-
-
-def get_media_indices(my_list):
- if isinstance(my_list, torch.Tensor):
- my_list = my_list.cpu().tolist()
- result = []
- for i in range(len(my_list)):
- if i == 0 and my_list[i] < 0:
- result.append(i)
- elif my_list[i] != my_list[i - 1] and my_list[i] < 0:
- result.append(i)
- return result
-
-
-def get_media_types(tensors, positions):
- if isinstance(tensors, torch.Tensor):
- tensors = tensors.cpu().tolist()
- result = []
- for pos in positions:
- result.append(tensors[pos])
- return result
-
-
-@add_start_docstrings(
- """
- mPLUG-Owl Model for generating text given an image and an optional text prompt.
- """,
- MPLUG_OWL_START_DOCSTRING,
-)
-class MplugOwlForConditionalGeneration(MplugOwlPreTrainedModel):
- config_class = MplugOwlConfig
- main_input_name = "pixel_values"
-
- def __init__(self, config: MplugOwlConfig):
- super().__init__(config)
-
- self.vision_model = MplugOwlVisionModel(config.vision_config)
-
- self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size))
- self.temporal_query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.visual_abstractor_config.hidden_size))
- self.abstractor = MplugOwlVisualAbstractorModel(config.visual_abstractor_config, config.text_config.hidden_size)
-
- # if config.use_decoder_only_language_model:
- # from llama.modeling_llama import LlamaForCausalLM
- language_model = AutoModelForCausalLM.from_config(config.text_config)
- # else:
- # language_model = AutoModelForSeq2SeqLM.from_config(config.text_config)
- self.language_model = language_model
-
- # Initialize weights and apply final processing
- self.post_init()
- self.main_input_name = "input_ids"
- from transformers import GenerationConfig
-
- self.generation_config = GenerationConfig(max_length=512, do_sample=True, top_k=3, pad_token_id=0, unk_token_id=0, bos_token_id=1, eos_token_id=2)
-
- # Hack Bloom
- if config.text_config.model_type == "bloom":
- bound_method = bloom_forward.__get__(self.language_model.transformer, self.language_model.transformer.__class__)
- setattr(self.language_model.transformer, "forward", bound_method)
-
- def get_input_embeddings(self):
- return self.language_model.get_input_embeddings()
-
- def set_input_embeddings(self, value):
- self.language_model.set_input_embeddings(value)
-
- def set_output_embeddings(self, new_embeddings):
- self.language_model.set_output_embeddings(new_embeddings)
-
- def get_output_embeddings(self) -> nn.Module:
- return self.language_model.get_output_embeddings()
-
- def get_encoder(self):
- return self.language_model.get_encoder()
-
- def get_decoder(self):
- return self.language_model.get_decoder()
-
- def _tie_weights(self):
- if not self.config.use_decoder_only_language_model:
- self.language_model.encoder.embed_tokens = self.language_model.shared
- self.language_model.decoder.embed_tokens = self.language_model.shared
-
- def _preprocess_accelerate(self):
- r"""
- Some pre-processing hacks to make the model `accelerate` compatible. Check
- https://github.com/huggingface/transformers/pull/21707 for more details.
- """
- hf_device_map = self.hf_device_map
-
- if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1:
- # warn users about unexpected behavior when using multi-GPU + mPLUG-Owl + `accelerate`.
- logger.warning(
- "The `language_model` is not in the `hf_device_map` dictionary and you are running your script"
- " in a multi-GPU environment. this may lead to unexpected behavior when using `accelerate`."
- " Please pass a `device_map` that contains `language_model` to remove this warning."
- " Please refer to https://github.com/huggingface/blog/blob/main/accelerate-large-models.md for"
- " more details on creating a `device_map` for large models.",
- )
-
- if hasattr(self.language_model, "_hf_hook"):
- self.language_model._hf_hook.io_same_device = True # For `generate` compatibility
-
- @add_start_docstrings_to_model_forward(MPLUG_OWL_INPUTS_DOCSTRING)
- @replace_return_docstrings(output_type=MplugOwlForConditionalGenerationModelOutput, config_class=MplugOwlVisionConfig)
- def forward(
- self,
- pixel_values: torch.FloatTensor,
- video_pixel_values: torch.FloatTensor,
- input_ids: torch.FloatTensor,
- num_images,
- num_videos,
- non_padding_mask: Optional[torch.LongTensor] = None,
- non_media_mask: Optional[torch.LongTensor] = None,
- prompt_mask: Optional[torch.LongTensor] = None,
- attention_mask: Optional[torch.LongTensor] = None,
- decoder_input_ids: Optional[torch.LongTensor] = None,
- decoder_attention_mask: Optional[torch.LongTensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- labels: Optional[torch.LongTensor] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, MplugOwlForConditionalGenerationModelOutput]:
- r"""
- Returns:
-
- Examples:
-
- Image captioning (without providing a text prompt):
-
- ```python
- >>> from PIL import Image
- >>> import requests
- >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration
- >>> import torch
-
- >>> device = "cuda" if torch.cuda.is_available() else "cpu"
-
- >>> processor = MplugOwlProcessor.from_pretrained("x-plug/x_plug-llama-7b")
- >>> model = MplugOwlForConditionalGeneration.from_pretrained(
- ... "x-plug/x_plug-llama-7b", torch_dtype=torch.float16
- ... )
- >>> model.to(device) # doctest: +IGNORE_RESULT
-
- >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
- >>> image = Image.open(requests.get(url, stream=True).raw)
-
- >>> inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
-
- >>> generated_ids = model.generate(**inputs)
- >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
- >>> print(generated_text)
- two cats laying on a couch
- ```
-
- Visual question answering (prompt = question):
-
- ```python
- >>> from PIL import Image
- >>> import requests
- >>> from transformers import MplugOwlProcessor, MplugOwlForConditionalGeneration
- >>> import torch
-
- >>> device = "cuda" if torch.cuda.is_available() else "cpu"
-
- >>> processor = MplugOwlProcessor.from_pretrained("x-plug/x_plug-llama-7b")
- >>> model = MplugOwlForConditionalGeneration.from_pretrained(
- ... "x-plug/x_plug-llama-7b", torch_dtype=torch.float16
- ... )
- >>> model.to(device) # doctest: +IGNORE_RESULT
-
- >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
- >>> image = Image.open(requests.get(url, stream=True).raw)
-
- >>> prompt = "Question: how many cats are there? Answer:"
- >>> inputs = processor(images=image, text=prompt, return_tensors="pt").to(device, torch.float16)
-
- >>> generated_ids = model.generate(**inputs)
- >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
- >>> print(generated_text)
- two
- ```"""
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- # get text embedding
- text_tokens_ = input_ids.clone()
- batch_size = input_ids.shape[0]
- # labels = text_tokens_[:, 1:].clone().contiguous()
-
- media_token_indices = [
- # [:-1] since we would not use the last token for embedding
- get_media_indices(text_tokens_[i][:-1])
- for i in range(batch_size)
- ]
-
- media_token_types = [get_media_types(text_tokens_[i][:-1], media_token_indices[i]) for i in range(batch_size)]
-
- text_tokens_[text_tokens_ < 0] = 1 # Not used
- # text_tokens = text_tokens_[:, :-1].contiguous()
- text_embeds = self.get_input_embeddings()(text_tokens_) # Temporally Embedding
-
- if pixel_values is not None:
- image_embeds = self.vision_model(pixel_values, return_dict=True).last_hidden_state
-
- image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
- query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
- temporal_query_tokens = self.temporal_query_tokens.expand(image_embeds.shape[0], -1, -1)
-
- query_features = self.abstractor(
- query_embeds=query_tokens,
- encoder_hidden_states=image_embeds,
- encoder_attention_mask=image_attention_mask,
- )["last_hidden_state"]
- img_seq_length = query_features.shape[1]
-
- if video_pixel_values is not None:
- video_embeds = self.vision_model(video_pixel_values, return_dict=True).last_hidden_state
-
- video_attention_mask = torch.ones(video_embeds.size()[:-1], dtype=torch.long, device=video_embeds.device)
- video_attention_mask = einops.rearrange(video_attention_mask, "b t n -> b (t n)")
- query_tokens = self.query_tokens.expand(video_embeds.shape[0], -1, -1)
- temporal_query_tokens = self.temporal_query_tokens.expand(video_embeds.shape[0], -1, -1)
-
- video_query_features = self.abstractor(
- query_embeds=query_tokens,
- temporal_query_embeds=temporal_query_tokens,
- encoder_hidden_states=video_embeds,
- encoder_attention_mask=video_attention_mask,
- )["last_hidden_state"]
- vid_seq_length = video_query_features.shape[1]
-
- num_images_per_sample = num_images.long().cpu().tolist()
- num_videos_per_sample = num_videos.long().cpu().tolist()
-
- text_chunk_embeds = []
- img_idx = 0
- for b in range(batch_size):
- start = 0
- result = []
- if len(media_token_indices[b]) > 0:
- for i, pos in enumerate(media_token_indices[b]):
- if pos > start:
- result.append(text_embeds[b, start:pos])
- result.append(query_features[img_idx + i])
- start = pos + img_seq_length
- if start < text_embeds.shape[1]:
- result.append(text_embeds[b, start:])
-
- img_idx += num_images_per_sample[b]
- text_chunk_embeds.append(torch.cat(result, dim=0))
-
- # Actual Input Embeddings
- input_embeds = torch.stack(text_chunk_embeds, dim=0)
-
- # if pixel_values is None and self.language_model.is_gradient_checkpointing:
- # # Hack here when gradient checkpoint is enable.
- # # Keep the compute graph static
- # image_embeds = self.vision_model(torch.zeros(1,3,224,224,device=input_embeds.device,dtype=input_embeds.dtype), return_dict=True).last_hidden_state
- # query_tokens = self.query_tokens.expand(
- # image_embeds.shape[0], -1, -1)
- # query_features = self.abstractor(query_embeds=query_tokens,
- # encoder_hidden_states=image_embeds,)['last_hidden_state']
-
- # input_embeds = input_embeds + query_features.mean()*0
-
- # Create causal mask and position ids
- _, loss_mask, position_ids = get_ltor_masks_and_position_ids_from_embeddings(input_embeds)
-
- # Calculate the loss_mask
- non_padding_mask = non_padding_mask.long()
- non_media_mask = non_media_mask.long()
- prompt_mask = prompt_mask.long() # TODO How to deal with prompt mask
- # from icecream import ic
- # non_padding_mask = non_padding_mask[:,:-1]
- # non_media_mask = non_media_mask[:,:-1]
- # prompt_mask = prompt_mask[:,:-1]
- # attention_mask = attention_mask[:,:-1]
- loss_mask = loss_mask[:, :-1]
-
- loss_mask = loss_mask * non_padding_mask * non_media_mask * prompt_mask
- labels[:, 1:][loss_mask != 1] = -100
- # Forward into GPT
- outputs = self.language_model(
- inputs_embeds=input_embeds,
- attention_mask=attention_mask,
- labels=labels,
- return_dict=return_dict,
- output_attentions=self.config.output_attentions,
- )
- # outputs.loss = (outputs.loss * loss_mask.view(-1)
- # ).sum()/loss_mask.sum()
- return outputs
-
- @torch.no_grad()
- def generate(
- self,
- pixel_values: torch.FloatTensor = None,
- video_pixel_values: torch.FloatTensor = None,
- input_ids: Optional[torch.LongTensor] = None,
- attention_mask: Optional[torch.LongTensor] = None,
- isdecoder=True,
- **generate_kwargs,
- ) -> torch.LongTensor:
- """
- Overrides `generate` function to be able to use the model as a conditional generator.
-
- Args:
- pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)):
- Input images to be processed.
- input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
- The sequence used as a prompt for the generation.
- attention_mask (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):
- Mask to avoid performing attention on padding token indices
-
- Returns:
- captions (list): A list of strings of length batch_size * num_captions.
- """
- if input_ids is None:
- return self.language_model.generate(attention_mask=attention_mask, **generate_kwargs)
-
- if attention_mask is None:
- attention_mask = input_ids.new_ones(*input_ids.shape)
-
- batch_size = input_ids.size(0)
- media_token_indices = [get_media_indices(input_ids[i]) for i in range(batch_size)]
- media_token_types = [get_media_types(input_ids[i], media_token_indices[i]) for i in range(batch_size)]
- num_images_per_sample = [len([y for y in x if y == -1]) for x in media_token_types]
- num_videos_per_sample = [len([y for y in x if y < -1]) for x in media_token_types]
- input_ids = input_ids.clone() # prevent inplace modify
- input_ids[input_ids < 0] = 0 # Not used
-
- if hasattr(self, "hf_device_map"):
- # preprocess for `accelerate`
- self._preprocess_accelerate()
- batch_size = input_ids.shape[0]
- # get text embedding
- inputs_embeds = self.get_input_embeddings()(input_ids)
- if hasattr(self.language_model, "transformer") and hasattr(self.language_model.transformer, "word_embeddings_layernorm"):
- inputs_embeds = self.language_model.transformer.word_embeddings_layernorm(inputs_embeds)
- # get visual embedding
- if pixel_values is not None:
- pixel_values = pixel_values.to(input_ids.device)
- with torch.no_grad():
- image_embeds = self.vision_model(pixel_values, return_dict=True).last_hidden_state
- image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
- query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
- query_outputs = self.abstractor(
- query_embeds=query_tokens,
- encoder_hidden_states=image_embeds,
- encoder_attention_mask=image_attention_mask,
- return_dict=True,
- )
- query_output = query_outputs["last_hidden_state"]
- image_embeds = query_output
- img_seq_length = image_embeds.shape[1]
-
- if video_pixel_values is not None:
- video_pixel_values = video_pixel_values.to(input_ids.device)
- with torch.no_grad():
- video_embeds = self.vision_model(video_pixel_values, return_dict=True).last_hidden_state
- video_attention_mask = torch.ones(video_embeds.size()[:-1], dtype=torch.long, device=video_embeds.device)
- video_attention_mask = einops.rearrange(video_attention_mask, "b t n -> b (t n)")
- query_tokens = self.query_tokens.expand(video_embeds.shape[0], -1, -1)
- temporal_query_tokens = self.temporal_query_tokens.expand(video_embeds.shape[0], -1, -1)
- query_outputs = self.abstractor(
- query_embeds=query_tokens,
- temporal_query_embeds=temporal_query_tokens,
- encoder_hidden_states=video_embeds,
- encoder_attention_mask=video_attention_mask,
- return_dict=True,
- )
- query_output = query_outputs["last_hidden_state"]
- video_embeds = query_output
- vid_seq_length = video_embeds.shape[1]
-
- # ===================
- # Get actual input embeddings
- # ===================
- text_chunk_embeds = []
- text_chunk_attns = []
- img_idx = 0
- vid_idx = 0
-
- for b in range(batch_size):
- start = 0
- result = []
- result_attn = []
- for i, pos in enumerate(media_token_indices[b]):
- curr_image_idx, curr_video_idx = 0, 0
- if pos > start:
- result.append(inputs_embeds[b, start:pos])
- result_attn.append(attention_mask[b, start:pos])
- if media_token_types[b][i] == -1:
- result.append(image_embeds[img_idx + curr_image_idx])
- result_attn.append(torch.ones(image_embeds[img_idx + curr_image_idx].shape[0], device=inputs_embeds.device))
- start = pos + img_seq_length
- curr_image_idx += 1
- else:
- result.append(video_embeds[vid_idx + curr_video_idx])
- result_attn.append(torch.ones(video_embeds[img_idx + curr_video_idx].shape[0], device=inputs_embeds.device))
- start = pos + vid_seq_length
- curr_video_idx += 1
- if start < inputs_embeds.shape[1]:
- result.append(inputs_embeds[b, start:])
- result_attn.append(attention_mask[b, start:])
-
- img_idx += num_images_per_sample[b]
- vid_idx += num_videos_per_sample[b]
- text_chunk_embeds.append(torch.cat(result, dim=0))
- text_chunk_attns.append(torch.cat(result_attn, dim=0))
- inputs_embeds = torch.stack(text_chunk_embeds, dim=0)
- attention_mask = torch.stack(text_chunk_attns, dim=0)
-
- outputs = self.language_model.generate(
- inputs_embeds=inputs_embeds,
- # input_ids=input_ids,
- attention_mask=attention_mask,
- **generate_kwargs,
- )
-
- return outputs
-
- def prepare_inputs_for_generation(self, input_ids, pixel_values=None, video_pixel_values=None, past_key_values=None, attention_mask=None, **model_kwargs):
- input_shape = input_ids.shape
- # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
- if attention_mask is None:
- attention_mask = input_ids.new_ones(input_shape)
-
- # # cut decoder_input_ids if past_key_values is used
- # if past_key_values is not None:
- # input_ids = input_ids[:, -1:]
-
- return {
- "input_ids": input_ids,
- "pixel_values": pixel_values,
- "video_pixel_values": video_pixel_values,
- "attention_mask": attention_mask,
- # "past_key_values": past_key_values,
- # "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
- # "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
- "is_decoder": True,
- }
-
-
-def bloom_forward(
- self,
- input_ids: Optional[torch.LongTensor] = None,
- past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.LongTensor] = None,
- inputs_embeds: Optional[torch.LongTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- **deprecated_arguments,
-) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
- if deprecated_arguments.pop("position_ids", False) is not False:
- # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
- warnings.warn(
- "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore" " passing `position_ids`.",
- FutureWarning,
- )
- if len(deprecated_arguments) > 0:
- raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
-
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- use_cache = use_cache if use_cache is not None else self.config.use_cache
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- if input_ids is not None and inputs_embeds is not None:
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
- elif input_ids is not None:
- batch_size, seq_length = input_ids.shape
- elif inputs_embeds is not None:
- batch_size, seq_length, _ = inputs_embeds.shape
- else:
- raise ValueError("You have to specify either input_ids or inputs_embeds")
-
- if past_key_values is None:
- past_key_values = tuple([None] * len(self.h))
-
- # Prepare head mask if needed
- # 1.0 in head_mask indicate we keep the head
- # attention_probs has shape batch_size x num_heads x N x N
- # head_mask has shape n_layer x batch x num_heads x N x N
- head_mask = self.get_head_mask(head_mask, self.config.n_layer)
-
- if inputs_embeds is None:
- inputs_embeds = self.word_embeddings(input_ids)
- inputs_embeds = self.word_embeddings_layernorm(inputs_embeds)
-
- hidden_states = inputs_embeds
-
- presents = () if use_cache else None
- all_self_attentions = () if output_attentions else None
- all_hidden_states = () if output_hidden_states else None
-
- if self.gradient_checkpointing and self.training:
- if use_cache:
- logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
- use_cache = False
-
- # Compute alibi tensor: check build_alibi_tensor documentation
- seq_length_with_past = seq_length
- past_key_values_length = 0
- if past_key_values[0] is not None:
- past_key_values_length = past_key_values[0][0].shape[2]
- seq_length_with_past = seq_length_with_past + past_key_values_length
- if attention_mask is None:
- attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
- else:
- attention_mask = attention_mask.to(hidden_states.device)
-
- alibi = self.build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
-
- causal_mask = self._prepare_attn_mask(
- attention_mask,
- input_shape=(batch_size, seq_length),
- past_key_values_length=past_key_values_length,
- )
-
- for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- if self.gradient_checkpointing and self.training:
-
- def create_custom_forward(module):
- def custom_forward(*inputs):
- # None for past_key_value
- return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
-
- return custom_forward
-
- outputs = torch.utils.checkpoint.checkpoint(
- create_custom_forward(block),
- hidden_states,
- alibi,
- causal_mask,
- layer_past,
- head_mask[i],
- )
- else:
- outputs = block(
- hidden_states,
- layer_past=layer_past,
- attention_mask=causal_mask,
- head_mask=head_mask[i],
- use_cache=use_cache,
- output_attentions=output_attentions,
- alibi=alibi,
- )
-
- hidden_states = outputs[0]
- if use_cache is True:
- presents = presents + (outputs[1],)
-
- if output_attentions:
- all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
-
- # Add last hidden state
- hidden_states = self.ln_f(hidden_states)
-
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- if not return_dict:
- return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
-
- return BaseModelOutputWithPastAndCrossAttentions(
- last_hidden_state=hidden_states,
- past_key_values=presents,
- hidden_states=all_hidden_states,
- attentions=all_self_attentions,
- )
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/processing_mplug_owl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/processing_mplug_owl.py
deleted file mode 100644
index 38cbf023f7c8a8651351f937d6409320e4bbdfde..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/processing_mplug_owl.py
+++ /dev/null
@@ -1,262 +0,0 @@
-import re
-import torch
-import torch.utils.checkpoint
-
-from transformers.processing_utils import ProcessorMixin
-from transformers.tokenization_utils_base import BatchEncoding
-from transformers.models.clip.image_processing_clip import CLIPImageProcessor
-from .tokenization_mplug_owl import MplugOwlTokenizer
-
-from decord import VideoReader
-import numpy as np
-from PIL import Image
-from lmms_eval.models.model_utils.load_video import read_video_pyav
-
-
-def get_index(num_frames, num_segments):
- seg_size = float(num_frames - 1) / num_segments
- start = int(seg_size / 2)
- offsets = np.array([start + int(np.round(seg_size * idx)) for idx in range(num_segments)])
- return offsets
-
-
-def load_video(path, num_frames=4):
- """vr = VideoReader(path, height=224, width=224)
- total_frames = len(vr)
- frame_indices = get_index(total_frames, num_frames)
- images_group = list()
- for frame_index in frame_indices:
- img = Image.fromarray(vr[frame_index].asnumpy()).convert("RGB")
- images_group.append(img)
- return images_group"""
- # Change a bit here from the original code
- # I use pyav instead of decord because it is much more safer
- # The operations here are the same, we load video and return a list of PIL Image
- # Load video frames
- video_frames = read_video_pyav(path, num_frm=num_frames)
- target_h, target_w = 224, 224
- # If image shape is not as target, resize it
- if video_frames.shape[-3] != target_h or video_frames.shape[-2] != target_w:
- video_frames = torch.from_numpy(video_frames).permute(0, 3, 1, 2).float()
- video_frames = torch.nn.functional.interpolate(video_frames, size=(target_h, target_w))
- video_frames = video_frames.permute(0, 2, 3, 1).to(torch.uint8).numpy()
- video_frames = [Image.fromarray(frame) for frame in video_frames]
- if len(video_frames) > num_frames:
- video_frames = video_frames[:num_frames]
- return video_frames
-
-
-class MplugOwlProcessor(ProcessorMixin):
- attributes = []
- tokenizer_class = "MplugOwlTokenizer"
-
- def __init__(self, image_processor=None, tokenizer=None, **kwargs):
- super().__init__(**kwargs)
- self.tokens_to_generate = 0
- self.image_processor = image_processor
- self.tokenizer = tokenizer
- self.add_BOS = True
-
- def __call__(self, text=None, images=None, videos=None, num_frames=4, return_tensors=None, **kwargs):
- if text is None and images is None:
- raise ValueError("You have to specify either text or images. Both cannot be none.")
-
- if text is not None:
- encoding = tokenize_prompts(
- prompts=text,
- tokens_to_generate=self.tokens_to_generate,
- add_BOS=self.add_BOS,
- tokenizer=self.tokenizer,
- ignore_dist=True,
- **kwargs,
- )
- # encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
-
- if images is not None:
- image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
-
- if videos is not None:
- video_features = []
- for video in videos:
- video_frames = load_video(video, num_frames)
- video_feature = self.image_processor(video_frames, return_tensors=return_tensors, **kwargs)["pixel_values"]
- video_features.append(video_feature)
- video_features = torch.stack(video_features, dim=0)
- video_features = video_features.permute(0, 2, 1, 3, 4)
-
- if text is not None and images is not None:
- encoding["pixel_values"] = image_features.pixel_values
- return encoding
- if text is not None and videos is not None:
- encoding["video_pixel_values"] = video_features
- return encoding
- elif text is not None:
- return encoding
- elif images is not None:
- return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
- else:
- return BatchEncoding(data=dict(video_pixel_values=video_pixel_values), tensor_type=return_tensors)
-
- def batch_decode(self, skip_special_tokens=True, *args, **kwargs):
- """
- This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
- refer to the docstring of this method for more information.
- """
- return self.tokenizer.batch_decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)
-
- def decode(self, skip_special_tokens=True, *args, **kwargs):
- """
- This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
- the docstring of this method for more information.
- """
- return self.tokenizer.decode(*args, skip_special_tokens=skip_special_tokens, **kwargs)
-
-
-class MplugOwlImageProcessor(CLIPImageProcessor):
- pass
-
-
-def detokenize_generations(tokens_gpu_tensor, lengths_gpu_tensor, return_segments, tokenizer):
- """Detokenize the generated tokens."""
-
- prompts_plus_generations = []
- if return_segments:
- prompts_plus_generations_segments = []
-
- tokens = tokens_gpu_tensor.cpu().numpy().tolist()
- lengths = lengths_gpu_tensor.cpu().numpy().tolist()
- for sequence_tokens, length in zip(tokens, lengths):
- sequence_tokens = sequence_tokens[:length]
- prompts_plus_generations.append(tokenizer.detokenize(sequence_tokens))
- if return_segments:
- from tokenizers.decoders import Metaspace
-
- if hasattr(tokenizer, "tokenizer"):
- if isinstance(tokenizer.tokenizer.decoder, Metaspace):
- words = tokenizer.tokenizer.decode(sequence_tokens)
- else:
- words = []
- for token in sequence_tokens:
- word = tokenizer.tokenizer.decoder[token]
- word = bytearray([tokenizer.tokenizer.byte_decoder[c] for c in word]).decode("utf-8", errors="replace")
- words.append(word)
- prompts_plus_generations_segments.append(words)
- else:
- words = tokenizer.detokenize(sequence_tokens)
- # else:
- # words = []
- # for token in sequence_tokens:
- # word = tokenizer.tokenizer.decoder[token]
- # word = bytearray(
- # [tokenizer.tokenizer.byte_decoder[c] for c in word]).decode(
- # 'utf-8', errors='replace')
- # words.append(word)
- prompts_plus_generations_segments.append(words)
-
- if return_segments:
- return tokens, prompts_plus_generations, prompts_plus_generations_segments
-
- return tokens, prompts_plus_generations
-
-
-def tokenize_prompts(prompts=None, tokens_to_generate=None, add_BOS=None, rank=0, tokenizer=None, ignore_dist=False, **kwargs):
- """Tokenize prompts and make them avaiable on all ranks."""
-
- # On all ranks set to None so we can pass them to functions
- prompts_tokens_cuda_long_tensor = None
- prompts_length_cuda_long_tensor = None
-
- # On the specified rank, build the above.
- attention_mask = None
- if ignore_dist or torch.distributed.get_rank() == rank:
- assert prompts is not None
- assert tokens_to_generate is not None
- # Tensor of tokens padded and their unpadded length.
- prompts_tokens_cuda_long_tensor, prompts_length_cuda_long_tensor, attention_mask = _tokenize_prompts_and_batch(prompts, tokens_to_generate, add_BOS, tokenizer, **kwargs)
- # We need the sizes of these tensors for the boradcast
- [
- prompts_tokens_cuda_long_tensor.size(0), # Batch size
- prompts_tokens_cuda_long_tensor.size(1),
- ] # Sequence lenght
-
- return {
- "input_ids": prompts_tokens_cuda_long_tensor,
- "attention_mask": attention_mask,
- # "prompt_length": prompts_length_cuda_long_tensor,
- }
-
-
-def _tokenize_prompts_and_batch(prompts, tokens_to_generate, add_BOS, tokenizer, **kwargs):
- """Given a set of prompts and number of tokens to generate:
- - tokenize prompts
- - set the sequence length to be the max of length of prompts
- plus the number of tokens we would like to generate
- - pad all the sequences to this length so we can convert them
- into a 2D tensor.
- """
-
- # Tokenize all the prompts.
- # if add_BOS:
- # prompts_tokens = [[tokenizer.bos] + tokenizer.tokenize(prompt)
- # for prompt in prompts]
- # else:
- # prompts_tokens = [tokenizer.tokenize(prompt) for prompt in prompts]
-
- prompts_tokens = [_tokenize_prompt(prompt, tokenizer, add_BOS, **kwargs) for prompt in prompts]
-
- # Now we have a list of list of tokens which each list has a different
- # size. We want to extend this list to:
- # - incorporate the tokens that need to be generated
- # - make all the sequences equal length.
- # Get the prompts length.
- prompts_length = [len(prompt_tokens) for prompt_tokens in prompts_tokens]
- # Get the max prompts length.
- max_prompt_len = max(prompts_length)
- # Number of tokens in the each sample of the batch.
- samples_length = max_prompt_len + tokens_to_generate
- # Now update the list of list to be of the same size: samples_length.
- for prompt_tokens, prompt_length in zip(prompts_tokens, prompts_length):
- padding_size = samples_length - prompt_length
- prompt_tokens.extend([tokenizer.eos_token_id] * padding_size)
-
- # Now we are in a structured format, we can convert to tensors.
- prompts_tokens_tensor = torch.LongTensor(prompts_tokens)
- prompts_length_tensor = torch.LongTensor(prompts_length)
- attention_mask = torch.zeros(prompts_tokens_tensor.shape[:2])
- for i, l in enumerate(prompts_length_tensor):
- attention_mask[i, :l] = 1
- return prompts_tokens_tensor, prompts_length_tensor, attention_mask
-
-
-def _tokenize_prompt(prompt, tokenizer, add_BOS=False, media_info={"": 65, "<|video|>": 65}, **kwargs):
- media_tokens = {k: -int(i + 1) for i, k in enumerate(media_info.keys())}
- media_lengths = media_info.copy()
-
- if add_BOS:
- prompt_chunk = [tokenizer.bos_token_id]
- else:
- prompt_chunk = []
-
- # Pure Text
- if all([media_token not in prompt for media_token in media_tokens.keys()]):
- enc_chunk = prompt_chunk + tokenizer(prompt, add_special_tokens=False, **kwargs)["input_ids"]
-
- # Multi-Modal Text
- else:
- enc_chunk = prompt_chunk
- pattern = "|".join(map(re.escape, list(media_tokens.keys())))
- chunk_strs = re.split(f"({pattern})", prompt)
- chunk_strs = [x for x in chunk_strs if len(x) > 0]
- for idx, chunk_str in enumerate(chunk_strs):
- if chunk_str in media_tokens:
- enc_chunk += [media_tokens[chunk_str]] * media_lengths[chunk_str]
- else:
- tmp_chunk = tokenizer(chunk_str, add_special_tokens=False)["input_ids"]
- # if idx < len(chunk_strs) - 1: # Last chunk should not have eos
- # tmp_chunk += [tokenizer.eod_id]
- enc_chunk += tmp_chunk
- return enc_chunk
-
-
-if __name__ == "__main__":
- pass
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/tokenization_mplug_owl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/tokenization_mplug_owl.py
deleted file mode 100644
index bd7f42f12148cf608ab4cf43fa3686e5b0459ef5..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/mplug_owl_video/tokenization_mplug_owl.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# coding=utf-8
-# Copyright 2022 x-plug and The HuggingFace Inc. team. All rights reserved.
-#
-# 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.
-"""Tokenization classes for MplugOwl."""
-
-from transformers.models.llama.tokenization_llama import LlamaTokenizer
-
-from loguru import logger
-
-VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
-
-PRETRAINED_VOCAB_FILES_MAP = {
- "vocab_file": {
- "MAGAer13/mplug-owl-llama-7b": "https://huggingface.co/MAGAer13/mplug-owl-llama-7b/resolve/main/vocab.txt",
- },
-}
-
-PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
- "MAGAer13/mplug-owl-llama-7b": 2048,
-}
-
-
-class MplugOwlTokenizer(LlamaTokenizer):
- def __init__(
- self,
- vocab_file,
- unk_token="",
- bos_token="",
- eos_token="",
- pad_token="",
- sp_model_kwargs=None,
- add_bos_token=False,
- add_eos_token=False,
- clean_up_tokenization_spaces=False,
- **kwargs,
- ):
- super().__init__(
- vocab_file,
- unk_token,
- bos_token,
- eos_token,
- pad_token,
- sp_model_kwargs,
- add_bos_token,
- add_eos_token,
- clean_up_tokenization_spaces,
- **kwargs,
- )
- self.eod_id = self.eos_token_id
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/phi3v.py b/lmms-eval-0.2.0.post1/lmms_eval/models/phi3v.py
deleted file mode 100644
index c30a70815c810c574c301368c3bf53b6450a9749..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/phi3v.py
+++ /dev/null
@@ -1,219 +0,0 @@
-import torch
-
-
-from accelerate import Accelerator, DistributedType
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from tqdm import tqdm
-from transformers import AutoModelForCausalLM
-from transformers import AutoProcessor
-from typing import List, Optional, Tuple, Union
-
-from loguru import logger as eval_logger
-
-
-@register_model("phi3v")
-class Phi3v(lmms):
- """
- This class implements inference for the microsoft/Phi-3-vision-128k-instruct model.
- To learn more about this model please visit the following links:
- 1. https://huggingface.co/microsoft/Phi-3-vision-128k-instruct
- 2. https://azure.microsoft.com/en-us/blog/new-models-added-to-the-phi-3-family-available-on-microsoft-azure/
- 3. https://github.com/microsoft/Phi-3CookBook
-
- NOTE: This class was adapted from quen_vl.py and llava_hf.py.
-
- Example:
-
- accelerate launch --num_processes=4 -m lmms_eval --model phi3v --tasks mmmu_val \
- --batch_size 1 --log_samples --log_samples_suffix phi3v_mmmu --output_path ./logs/
- """
-
- def __init__(
- self,
- model_id_name: str = "microsoft/Phi-3-vision-128k-instruct",
- device: str = "cuda",
- dtype: Optional[Union[str, torch.dtype]] = "auto",
- batch_size: int = 1,
- trust_remote_code: Optional[bool] = True,
- use_cache: bool = True,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
- # Setup accelerator.
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- else:
- self._device = device
- # Load model.
- self._model = AutoModelForCausalLM.from_pretrained(model_id_name, device_map=device, trust_remote_code=trust_remote_code, torch_dtype=dtype)
- self._processor = AutoProcessor.from_pretrained(model_id_name, trust_remote_code=trust_remote_code)
- self._processor.tokenizer.padding_side = "left"
- self._tokenizer = self._processor.tokenizer
- self._config = self._model.config
- self.batch_size_per_gpu = int(batch_size)
- assert self.batch_size_per_gpu == 1, "batch_size_per_gpu > 1 is not supported for now."
- self.use_cache = use_cache
- if accelerator.num_processes > 1:
- distributed_type_list = [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED]
- assert accelerator.distributed_type in distributed_type_list, "Unsupported distributed type provided. Only DDP and FSDP are supported."
- if accelerator.distributed_type == DistributedType.FSDP:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- raise NotImplementedError("Not implemented for Phi3v.")
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tokenizer.encode(x[0])
- return -len(toks), x[0]
-
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals)
- # We assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
- # Set default values for until and max_new_tokens
- until = [self.tokenizer.decode(self.eot_token_id)]
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
- if isinstance(contexts, tuple):
- contexts = list(contexts)
- for i in range(len(contexts)):
- if "" in contexts[i]:
- query = "" + contexts[i]
- img_placeholder_count = 1
- while "" in query:
- query = query.replace("", f"<|image_{img_placeholder_count}|>", 1)
- img_placeholder_count += 1
- else:
- query = ""
- for placeholder_id in range(len(visuals)):
- query += f"<|image_{placeholder_id+1}|>\n"
- query += contexts[i]
- messages = [{"role": "user", "content": query}]
- contexts[i] = self._tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
- assert len(contexts) == 1
- #
- context = contexts[0]
- input_ids = self._processor(text=context, images=visuals, return_tensors="pt").to(self._device, self.model.dtype)
- # Setting default parameters.
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
- # Generate answer.
- pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eod_id
- generate_ids = self.model.generate(
- **input_ids,
- eos_token_id=self.tokenizer.eos_token_id,
- pad_token_id=pad_token_id,
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- use_cache=self.use_cache,
- )
- generate_ids = generate_ids[:, input_ids["input_ids"].shape[1] :]
- response = self._processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
- res.append(response)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), response)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl.py b/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl.py
deleted file mode 100644
index dff301d30c6177f50d8c17fdfbdf4991393b9d8e..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl.py
+++ /dev/null
@@ -1,309 +0,0 @@
-import torch
-
-from tqdm import tqdm
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.models.model_utils.qwen.qwen_generate_utils import make_context
-from accelerate import Accelerator, DistributedType
-from typing import List, Optional, Union, Tuple
-import uuid
-import os
-
-import warnings
-
-warnings.simplefilter("ignore", category=DeprecationWarning)
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-
-@register_model("qwen_vl")
-class Qwen_VL(lmms):
- """
- Qwen_VL Model
- https://github.com/QwenLM/Qwen-VL/blob/master/eval_mm/evaluate_vqa.py
- """
-
- def __init__(
- self,
- pretrained: str = "Qwen/Qwen-VL",
- device: Optional[str] = "cuda",
- batch_size: Optional[Union[int, str]] = 1,
- trust_remote_code: Optional[bool] = True,
- use_cache=True,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- else:
- self._device = device
- self._model = AutoModelForCausalLM.from_pretrained(pretrained, device_map=self._device, trust_remote_code=trust_remote_code).eval()
- self._tokenizer = AutoTokenizer.from_pretrained(pretrained, trust_remote_code=trust_remote_code)
- self.tokenizer.padding_side = "left"
- self.tokenizer.pad_token_id = self.tokenizer.eod_id
- self.prompt = "
{}{}"
- self._config = self._model.config
- self.model.tie_weights()
- self.batch_size_per_gpu = int(batch_size)
- self.use_cache = use_cache
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [
- DistributedType.FSDP,
- DistributedType.MULTI_GPU,
- ], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- if accelerator.distributed_type == DistributedType.FSDP:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.model.to(self._device)
- self._rank = 0
- self._word_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eod_id
-
- @property
- def max_length(self):
- return self._max_length
-
- # should be deleted since max_new_tokens is decided by gen_kwargs not a model property
- # @property
- # def max_new_tokens(self) -> int:
- # return 256
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- query = []
- visual_paths = []
- for visual in visuals:
- name = uuid.uuid4().hex.upper()[0:6]
- visual.save(f"/tmp/{name}.png")
- visual_paths.append(f"/tmp/{name}.png")
- query.append({"image": f"/tmp/{name}.png"})
-
- # Make a copy for query to save context (text that needs to be masked)
- context_query = [_ for _ in query]
- context_query.append({"text": contexts})
- query.append({"text": contexts + continuation})
-
- context_query = self.tokenizer.from_list_format(context_query)
- query = self.tokenizer.from_list_format(query)
-
- raw_contxt_text, context_tokens = make_context(
- self.tokenizer, context_query, history=None, system="You are a helpful assistant", max_window_size=self.model.generation_config.max_window_size, chat_format=self.model.generation_config.chat_format
- )
- context_tokens = torch.tensor([context_tokens])
-
- raw_continuation_text, continuation_tokens = make_context(
- self.tokenizer, query, history=None, system="You are a helpful assistant", max_window_size=self.model.generation_config.max_window_size, chat_format=self.model.generation_config.chat_format
- )
- continuation_tokens = torch.tensor([continuation_tokens]).to(self.model.device)
- attn_mask = torch.ones_like(continuation_tokens).to(self.model.device)
- labels = continuation_tokens.clone().to(self.model.device)
- labels[:, : context_tokens.shape[1]] = -100
- with torch.inference_mode():
- outputs = self.model(input_ids=continuation_tokens, labels=labels, attention_mask=attn_mask)
- loss = outputs.loss
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = continuation_tokens[:, context_tokens.shape[1] :]
- greedy_tokens = greedy_tokens[:, context_tokens.shape[1] : continuation_tokens.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
-
- pbar.close()
- return res
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tokenizer.encode(x[0])
- return -len(toks), x[0]
-
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id]
- visuals = self.flatten(visuals)
- visual_paths = []
- # save images to /tmp, name generated by hash function
- # qwen accept image path. Have to do it here....
- for visual in visuals:
- name = uuid.uuid4().hex.upper()[0:6]
- visual.save(f"/tmp/{name}.png")
- visual_paths.append(f"/tmp/{name}.png")
-
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tokenizer.decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
-
- if isinstance(contexts, tuple):
- contexts = list(contexts)
-
- for i in range(len(contexts)):
- if "" in contexts[i]:
- contexts[i] = contexts[i].replace("", "")
-
- # Similar to llava, is visual paths has len 0
- # Then nothing will be executed
- query = []
- if len(visual_paths) == 0:
- for context in contexts:
- query.append({"text": context})
- else:
- for visual_path, context in zip(visual_paths, contexts):
- query.append({"image": visual_path})
- query.append({"text": context})
-
- questions = self.tokenizer.from_list_format(query)
- input_ids = self.tokenizer(questions, return_tensors="pt", padding="longest")
-
- # preconfigure gen_kwargs with defaults
- if "image_sizes" not in gen_kwargs:
- try:
- gen_kwargs["image_sizes"] = [visuals[0].size]
- except:
- gen_kwargs["image_sizes"] = None
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eod_id
-
- cont = self.model.generate(
- input_ids.input_ids.to(self.device),
- attention_mask=input_ids.attention_mask.to(self.device),
- eos_token_id=self.tokenizer.eod_id,
- pad_token_id=pad_token_id,
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- use_cache=self.use_cache,
- # kwargs=gen_kwargs
- )
-
- cont_toks_list = cont.tolist()
- for cont_toks, context in zip(cont_toks_list, contexts):
- # discard context + left-padding toks if using causal decoder-only LMM
- cont_toks = cont_toks[input_ids.input_ids.shape[1] :]
- text_outputs = self.tokenizer.decode(cont_toks, skip_special_tokens=True).strip()
- for term in until:
- if len(term) > 0:
- # ignore '' separator,
- # for seq2seq case where self.tok_decode(self.eot_token_id) = ''
- text_outputs = text_outputs.split(term)[0]
-
- res.append(text_outputs)
-
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- # remove visuals from tmp
- for visual_path in visual_paths:
- try:
- os.remove(visual_path)
- except:
- pass
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl_api.py b/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl_api.py
deleted file mode 100644
index 8a0ccc653a2292761c016b34c71bd1c36de0a86f..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/qwen_vl_api.py
+++ /dev/null
@@ -1,124 +0,0 @@
-from io import BytesIO
-from copy import deepcopy
-import os
-import base64
-from typing import List, Tuple, Union
-from tqdm import tqdm
-import requests as url_requests
-import time
-
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval import utils
-
-from PIL import Image
-
-NUM_SECONDS_TO_SLEEP = 5
-from loguru import logger as eval_logger
-
-try:
- import dashscope
-except:
- eval_logger.debug("Can not import Dashscope")
-
-API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
-
-
-@register_model("qwen-vl-api")
-class Qwen_VL_API(lmms):
- def __init__(
- self,
- model_version: str = "qwen-vl-max",
- image_token: str = "", # Use to separate interleaved image and text
- system_prompt: str = "", # Whether you want some special system prompt here
- tmp_folder: str = "./tmp", # Due to qwen's api restriction,
- **kwargs,
- ) -> None:
- super().__init__()
-
- self.model_version = model_version
- self.image_token = image_token
- self.system_prompt = system_prompt
- self.tmp_folder = tmp_folder
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
- os.makedirs(self.tmp_folder, exist_ok=True)
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- imgs = []
-
- for idx, visual in enumerate(visuals):
- visual.save(os.path.join(self.tmp_folder, f"tmp_{idx}_{self.rank}_{self.world_size}.jpg"))
- imgs.append(os.path.join(self.tmp_folder, f"tmp_{idx}_{self.rank}_{self.world_size}.jpg"))
-
- messages = [{"role": "user", "content": []}]
-
- if self.image_token not in contexts:
- for img in imgs:
- messages[0]["content"].append({"image": img})
- messages[0]["content"].append({"text": contexts})
- else:
- contexts = contexts.split(self.image_token)
-
- for idx, img in enumerate(imgs):
- messages[0]["content"].append({"text": contexts[idx]})
- messages[0]["content"].append({"image": img})
- messages[0]["content"].append({"text": contexts[-1]})
-
- if "max_new_tokens" not in gen_kwargs or gen_kwargs["max_new_tokens"] > 1500:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- for attempt in range(5):
- try:
- response_data = dashscope.MultiModalConversation.call(model=self.model_version, messages=messages, api_key=API_KEY, max_length=gen_kwargs["max_new_tokens"])
- except Exception as e:
- eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
- if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
- time.sleep(NUM_SECONDS_TO_SLEEP)
- else: # If this was the last attempt, log and return empty
- eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
- res.append("")
- pbar.update(1)
- continue
- try:
- res.append(response_data["output"]["choices"][0]["message"]["content"][0]["text"].strip())
- except Exception as e:
- eval_logger.error(f"Error {e} happens when parsing input.")
- eval_logger.error(f"{response_data}")
- res.append("")
- pbar.update(1)
-
- pbar.close()
-
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- assert False, "Not supported for claude"
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/reka.py b/lmms-eval-0.2.0.post1/lmms_eval/models/reka.py
deleted file mode 100644
index bc461caddc49fabb584ab7e4fda7adc813092d8b..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/reka.py
+++ /dev/null
@@ -1,192 +0,0 @@
-from PIL import Image
-from io import BytesIO
-from copy import deepcopy
-import numpy as np
-import os
-import base64
-from typing import List, Tuple
-from tqdm import tqdm
-import requests as url_requests
-import time
-
-import json
-
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from accelerate import Accelerator, DistributedType
-
-NUM_SECONDS_TO_SLEEP = 30
-
-from loguru import logger
-
-eval_logger = logger
-
-try:
- from reka.client import Reka as RekaClient
- from reka import ChatMessage
- from decord import VideoReader, cpu
-except Exception as e:
- eval_logger.warning(f"Error importing reka: {e}")
-
-
-@register_model("reka")
-class Reka(lmms):
- def __init__(
- self,
- model_version: str = "reka-edge",
- modality: str = "image",
- max_frames_for_video: int = 10,
- timeout: int = 120,
- continual_mode: bool = False,
- response_persistent_folder: str = None, # We will cache the Gemini API response in this path and use it for future requests
- **kwargs,
- ) -> None:
- super().__init__()
- self.model_version = model_version
- self.modality = modality
- self.max_frames_for_video = max_frames_for_video
- self.timeout = timeout
- self.continual_mode = continual_mode
- if self.continual_mode and response_persistent_folder is None:
- raise ValueError("Continual mode requires a persistent path for the response. Please provide a valid path.")
- self.response_persistent_folder = response_persistent_folder
- self.response_persistent_file = os.path.join(self.response_persistent_folder, f"{self.model_version}_response.json")
-
- if os.path.exists(self.response_persistent_file):
- with open(self.response_persistent_file, "r") as f:
- self.response_cache = json.load(f)
- self.cache_mode = "resume"
- else:
- self.response_cache = {}
- self.cache_mode = "start"
-
- self.reka = RekaClient(api_key=os.getenv("REKA_API_KEY", "YOUR_API_KEY"))
-
- accelerator = Accelerator()
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- else:
- self.accelerator = accelerator
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
-
- self.device = self.accelerator.device
-
- def encode_image(self, image):
- if type(image) == list:
- media_urls = []
- for img in image:
- output_buffer = BytesIO()
- img.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- media_urls.append(f"data:image/jpeg;base64,{base64_str}")
- return media_urls
- else:
- output_buffer = BytesIO()
- image.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
-
- return f"data:image/jpeg;base64,{base64_str}"
-
- def encode_video(self, video_path):
- vr = VideoReader(video_path, ctx=cpu(0))
- total_frame_num = len(vr)
- uniform_sampled_frames = np.linspace(0, total_frame_num - 1, self.max_frames_for_video, dtype=int)
- frame_idx = uniform_sampled_frames.tolist()
- frames = vr.get_batch(frame_idx).asnumpy()
-
- base64_frames = []
- for frame in frames:
- img = Image.fromarray(frame)
- output_buffer = BytesIO()
- img.save(output_buffer, format="PNG")
- byte_data = output_buffer.getvalue()
- base64_str = base64.b64encode(byte_data).decode("utf-8")
- base64_frames.append(f"data:image/jpeg;base64,{base64_str}")
-
- return base64_frames
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for context, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- if self.continual_mode is True and self.cache_mode == "resume":
- doc_uuid = f"{task}___{split}___{doc_id}"
- if doc_uuid in self.response_cache:
- response_text = self.response_cache[doc_uuid]
- if response_text:
- res.append(response_text)
- pbar.update(1)
- continue
-
- visual = doc_to_visual(self.task_dict[task][split][doc_id])
-
- message_content = []
-
- if self.modality == "image":
- media_urls = self.encode_image(visual)
- message_content.append({"type": "text", "text": context})
- for media_url in media_urls:
- message_content.append({"type": "image_url", "image_url": media_url})
- elif self.modality == "video":
- message_content.append({"type": "text", "text": context})
- assert len(visual) == 1, "Reka only supports one video per request"
- media_urls = self.encode_video(visual[0])
- assert len(media_urls) == self.max_frames_for_video, f"Reka only supports {self.max_frames_for_video} frames per request"
- for media_url in media_urls:
- message_content.append({"type": "image_url", "image_url": media_url})
-
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- for attempt in range(5):
- try:
- response = self.reka.chat.create(
- messages=[
- ChatMessage(
- role="user",
- content=message_content,
- )
- ],
- model=self.model_version,
- )
- response_text = response.responses[0].message.content.strip()
- break # If successful, break out of the loop
-
- except Exception as e:
- eval_logger.info(f"Attempt {attempt + 1} failed with error: {str(e)}")
- if attempt < 5 - 1: # If we have retries left, sleep and then continue to next attempt
- time.sleep(NUM_SECONDS_TO_SLEEP)
- else: # If this was the last attempt, log and return empty
- eval_logger.error(f"All 5 attempts failed. Last error message: {str(e)}")
- response_text = ""
-
- res.append(response_text)
- pbar.update(1)
- if self.continual_mode is True: # Cache the response
- doc_uuid = f"{task}___{split}___{doc_id}"
- self.response_cache[doc_uuid] = response_text
- with open(self.response_persistent_file, "w") as f:
- json.dump(self.response_cache, f)
-
- pbar.close()
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- assert False, "Reka not support loglikelihood"
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/tinyllava.py b/lmms-eval-0.2.0.post1/lmms_eval/models/tinyllava.py
deleted file mode 100644
index e07c47b8546667f2d7f69568f8f4c5ad0bf67e7d..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/tinyllava.py
+++ /dev/null
@@ -1,411 +0,0 @@
-import torch
-
-torch.backends.cuda.matmul.allow_tf32 = True
-
-
-import copy
-from tqdm import tqdm
-from datetime import timedelta
-
-from lmms_eval import utils
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-from lmms_eval.utils import stop_sequences_criteria
-
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from typing import List, Optional, Union, Tuple
-from packaging import version
-import warnings
-
-warnings.filterwarnings("ignore")
-
-from loguru import logger as eval_logger
-
-try:
- from tinyllava.model import load_pretrained_model
- from tinyllava.data import ImagePreprocess, TextPreprocess
- from tinyllava.utils.constants import DEFAULT_IMAGE_TOKEN
- from tinyllava.utils.message import Message
-except Exception as e:
- eval_logger.debug("TinyLLaVA_Factory is not installed. Please install TinyLLaVA_Factory to use this model.\nError: %s" % e)
-
-# inference implementation for attention, can be "sdpa", "eager", "flash_attention_2". Seems FA2 is not effective during inference: https://discuss.huggingface.co/t/flash-attention-has-no-effect-on-inference/73453/5
-# if is_flash_attn_2_available:
-# best_fit_attn_implementation = "flash_attention_2" # flash_attn has a bug that says: ERROR Error query and key must have the same dtype in generating
-
-if version.parse(torch.__version__) >= version.parse("2.1.2"):
- best_fit_attn_implementation = "sdpa"
-else:
- best_fit_attn_implementation = "eager"
-
-
-@register_model("tinyllava")
-class TinyLlava(lmms):
- """
- TinyLlava Model
- """
-
- def __init__(
- self,
- pretrained: str = "tinyllava/TinyLLaVA-Phi-2-SigLIP-3.1B",
- device: Optional[str] = "cuda:0",
- batch_size: Optional[Union[int, str]] = 1,
- device_map="cuda:0",
- conv_mode="phi", # TODO
- use_cache=True,
- **kwargs,
- ) -> None:
- super().__init__()
- # Do not use kwargs for now
- assert kwargs == {}, f"Unexpected kwargs: {kwargs}"
-
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
-
- self._model, self._tokenizer, self._image_processor, self._max_length = load_pretrained_model(pretrained, device_map=self.device_map)
- data_args = self._model.config
- self._image_processor = ImagePreprocess(self._image_processor, data_args)
- assert self._tokenizer.padding_side == "right", "Not sure but seems like `right` is a natural choice for padding?"
- self._text_processor = TextPreprocess(self._tokenizer, conv_mode)
-
- self._config = self._model.config
- self.model.eval()
- self.model.tie_weights()
- # self.truncation = truncation
- self.batch_size_per_gpu = int(batch_size)
- # self.conv_template = conv_template
- self.use_cache = use_cache
- # self.truncate_context = truncate_context
-
- # assert self.batch_size_per_gpu == 1, "Llava currently does not support batched generation. See https://github.com/haotian-liu/LLaVA/issues/754. HF Llava also has this issue."
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
-
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- @property
- def config(self):
- # return the associated transformers.AutoConfig for the given pretrained model.
- return self._config
-
- @property
- def tokenizer(self):
- return self._tokenizer
-
- @property
- def model(self):
- # returns the model, unwrapping it if using Accelerate
- if hasattr(self, "accelerator"):
- return self.accelerator.unwrap_model(self._model)
- else:
- return self._model
-
- @property
- def eot_token_id(self):
- # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
- return self.tokenizer.eos_token_id
-
- @property
- def max_length(self):
- return self._max_length
-
- def pad_sequence(self, input_ids, batch_first, padding_value):
- if self.tokenizer.padding_side == "left":
- input_ids = [torch.flip(_input_ids, [0]) for _input_ids in input_ids]
- input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=batch_first, padding_value=padding_value)
- if self.tokenizer.padding_side == "left":
- input_ids = torch.flip(input_ids, [1])
- return input_ids
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
-
- def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]:
- """ """
- add_special_tokens = False if add_special_tokens is None else add_special_tokens
- encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
- # left-truncate the encoded context to be at most `left_truncate_len` tokens long
- if left_truncate_len:
- encoding = encoding[-left_truncate_len:]
- return encoding
-
- def tok_decode(self, tokens):
- try:
- return self.tokenizer.decode(tokens)
- except:
- return self.tokenizer.decode([tokens])
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- # TODO
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- image_sizes = [[visual.size[0], visual.size[1]] for visual in visuals]
- if visuals:
- # https://github.com/zjysteven/TinyLLaVA_Factory/blob/main/tinyllava/data/image_preprocess.py
- # tinyllava's image processor seems to take each individual image as input
- image = [self._image_processor(v) for v in visuals]
- if type(image) is list:
- image = [_image.to(dtype=torch.float16, device=self.device) for _image in image]
- # as of 2024/06, tinyllava only accepts `images` input to be a tensor
- image = torch.stack(image)
- else:
- image = image.to(dtype=torch.float16, device=self.device)
- else:
- image = None
-
- prompts_input = contexts[0] if isinstance(contexts, list) else contexts
-
- if image is not None and len(image) != 0 and DEFAULT_IMAGE_TOKEN not in prompts_input:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- """
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visuals)
- image_tokens = " ".join(image_tokens)
- prompts_input = image_tokens + "\n" + (contexts[0] if isinstance(contexts, list) else contexts)
-
- msg = Message()
- msg.add_message(prompts_input)
- contxt_id = self._text_processor(msg.messages, mode="eval")["input_ids"]
- # Add the answer of the second role
- msg._messages[1]["value"] = continuation
- input_ids = self._text_processor(msg.messages, mode="eval")["input_ids"]
-
- labels = input_ids.clone()
- # Context part no need to calculate for loss
- labels[0, : contxt_id.shape[1]] = -100
-
- with torch.inference_mode():
- outputs = self.model(input_ids=input_ids, labels=labels, images=image, use_cache=True, image_sizes=image_sizes)
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = input_ids[:, contxt_id.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, contxt_id.shape[1] : input_ids.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
- pbar.close()
- return res
-
- def generate_until(self, requests: List[Instance]) -> List[str]:
- res = []
-
- def _collate(x):
- # the negative sign on len(toks) sorts descending - this has a few advantages:
- # - time estimates will always be over not underestimates, which is more useful for planning
- # - to know the size of a batch when going through the list, you know the first one is always the batch
- # padded context length. this is useful to simplify the batching logic and more importantly to make
- # automatic adaptive batches much much easier to implement
- # - any OOMs will happen right away rather than near the end
- toks = self.tok_encode(x[0])
- return -len(toks), x[0]
-
- # we group requests by their generation_kwargs,
- # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
- # in the same batch.
- re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True)
- chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None)
- num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1
- pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding")
- for chunk in chunks:
- contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk)
- task = task[0]
- split = split[0]
- batched_visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id] # [B, N]
- flattened_visuals = self.flatten(batched_visuals) # [B*N]
- # we assume all gen kwargs in the batch are the same
- # this is safe to assume because the `grouper` object ensures it.
- gen_kwargs = all_gen_kwargs[0]
-
- # Set default values for until and max_new_tokens
- until = [self.tok_decode(self.eot_token_id)]
-
- # Update values from gen_kwargs if present
- if "until" in gen_kwargs:
- until = gen_kwargs.pop("until")
- if isinstance(until, str):
- until = [until]
- elif not isinstance(until, list):
- raise ValueError(f"Expected `gen_kwargs['until']` to be of type Union[str,list] but got {type(until)}")
-
- if "image_aspect_ratio" in gen_kwargs.keys() and "image_aspect_ratio" not in self._config.__dict__:
- # here we should pop it out of gen_kwargs so that it doesn't get passed to the model for next step of generation
- self._config.image_aspect_ratio = gen_kwargs.pop("image_aspect_ratio")
- eval_logger.info(f"Setting image aspect ratio: {self._config.image_aspect_ratio}")
- # encode, pad, and truncate contexts for this batch
- if flattened_visuals:
- image_tensor = [self._image_processor(v) for v in flattened_visuals]
- if type(image_tensor) is list:
- image_tensor = [_image.to(dtype=torch.float16, device=self.device) for _image in image_tensor]
- # as of 2024/06, tinyllava only accepts `images` input to be a tensor
- image_tensor = torch.stack(image_tensor)
- else:
- image_tensor = image_tensor.to(dtype=torch.float16, device=self.device)
- else:
- image_tensor = None
-
- # prompts_input = contexts[0]
-
- question_input = []
-
- for visual, context in zip(batched_visuals, contexts):
- if image_tensor is not None and len(image_tensor) != 0 and DEFAULT_IMAGE_TOKEN not in context:
- """
- Three senarios:
- 1. No image, and there for, no image token should be added.
- 2. image token is already specified in the context, so we don't need to add it.
- 3. image token is not specified in the context and there is image inputs, so we need to add it. In this case, we add the image token at the beginning of the context and add a new line.
- """
- image_tokens = [DEFAULT_IMAGE_TOKEN] * len(visual) if isinstance(visual, list) else [DEFAULT_IMAGE_TOKEN]
- image_tokens = " ".join(image_tokens)
- question = image_tokens + "\n" + context
- else:
- question = context
-
- msg = Message()
- msg.add_message(question)
- prompt_question = self._text_processor(msg.messages, mode="eval")["prompt"]
- question_input.append(prompt_question)
-
- # The above for loop has bugs. When there is no visuals, e.g. pure text,
- # there will be no for loop execute resulting in an empty question_input (because no visuals)
- # Scenario 1 won't even be execute
- if len(flattened_visuals) == 0:
- for context in contexts:
- question = context
- msg = Message()
- msg.add_message(question)
- prompt_question = self._text_processor(msg.messages, mode="eval")["prompt"]
- question_input.append(prompt_question)
-
- # input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(self.device)
- # preconfigure gen_kwargs with defaults
- gen_kwargs["image_sizes"] = [flattened_visuals[idx].size for idx in range(len(flattened_visuals))]
- if "max_new_tokens" not in gen_kwargs:
- gen_kwargs["max_new_tokens"] = 1024
- if "temperature" not in gen_kwargs:
- gen_kwargs["temperature"] = 0
- if "top_p" not in gen_kwargs:
- gen_kwargs["top_p"] = None
- if "num_beams" not in gen_kwargs:
- gen_kwargs["num_beams"] = 1
-
- # input_ids_list = [tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt") for prompt in question_input]
- input_ids_list = [self._text_processor.template.tokenizer_image_token(prompt, self.tokenizer, return_tensors="pt") for prompt in question_input]
- pad_token_ids = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
- input_ids = self.pad_sequence(input_ids_list, batch_first=True, padding_value=pad_token_ids).to(self.device)
- attention_masks = input_ids.ne(pad_token_ids).to(self.device)
- # These steps are not in LLaVA's original code, but are necessary for generation to work
- # TODO: attention to this major generation step...
- try:
- cont = self.model.generate(
- input_ids,
- attention_mask=attention_masks,
- pad_token_id=pad_token_ids,
- images=image_tensor,
- image_sizes=gen_kwargs["image_sizes"],
- do_sample=True if gen_kwargs["temperature"] > 0 else False,
- temperature=gen_kwargs["temperature"],
- top_p=gen_kwargs["top_p"],
- num_beams=gen_kwargs["num_beams"],
- max_new_tokens=gen_kwargs["max_new_tokens"],
- use_cache=self.use_cache,
- )
- text_outputs = self.tokenizer.batch_decode(cont, skip_special_tokens=True)
- except Exception as e:
- raise e
- eval_logger.error(f"Error {e} in generating")
- cont = ""
- text_outputs = [""]
-
- # cont_toks_list = cont.tolist()
- # for cont_toks, context in zip(cont_toks_list, contexts):
- # discard context + left-padding toks if using causal decoder-only LMM
- # if self.truncate_context:
- # cont_toks = cont_toks[input_ids.shape[1] :]
- # use secondary stop seqs to cut off should-have-been-stopped content post-hoc
- # if self.truncate_context:
- # for term in until:
- # if len(term) > 0:
- # # ignore '' separator,
- # # for seq2seq case where self.tok_decode(self.eot_token_id) = ''
- # text_outputs = text_outputs.split(term)[0]
- res.extend(text_outputs)
- self.cache_hook.add_partial("generate_until", (context, gen_kwargs), text_outputs)
- pbar.update(1)
- # reorder this group of results back to original unsorted form
- res = re_ords.get_original(res)
-
- pbar.close()
- return res
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt.py b/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt.py
deleted file mode 100644
index 089a2c5dff3328d9473316dff93e84b6a7b34a0a..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt.py
+++ /dev/null
@@ -1,199 +0,0 @@
-import os
-from lmms_eval.api.instance import Instance
-from lmms_eval.api.model import lmms
-from lmms_eval.api.registry import register_model
-
-from accelerate import Accelerator, DistributedType, InitProcessGroupKwargs
-from accelerate.state import AcceleratorState
-from huggingface_hub import snapshot_download
-import torch
-from PIL import Image
-
-from datetime import timedelta
-from typing import List, Tuple, Optional, Union
-from tqdm import tqdm
-
-from loguru import logger
-
-eval_logger = logger
-
-try:
- from lmms_eval.models.video_chatgpt.eval.model_utils import load_video, initialize_model
- from lmms_eval.models.video_chatgpt.inference import video_chatgpt_infer, video_chatgpt_infer_ppl, get_spatio_temporal_features_torch
-except ImportError:
- eval_logger.warning("Failed to import video_chatgpt modules")
-
-from lmms_eval.models.model_utils.load_video import read_video_pyav
-
-
-@register_model("video_chatgpt")
-class VideoChatGPT(lmms):
- def __init__(
- self,
- batch_size: Optional[Union[int, str]] = 1,
- projection_path: str = "MBZUAI/Video-ChatGPT-7B",
- model_path: str = "mmaaz60/LLaVA-7B-Lightening-v1-1",
- device_map="cuda:0",
- device: Optional[str] = "cuda:0",
- num_frm: Optional[Union[int, str]] = 100,
- ) -> None:
- super().__init__()
- self.batch_size_per_gpu = int(batch_size)
- self.num_frm = int(num_frm)
- accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
- accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
- if accelerator.num_processes > 1:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- elif accelerator.num_processes == 1 and device_map == "auto":
- self._device = torch.device(device)
- self.device_map = device_map
- else:
- self._device = torch.device(f"cuda:{accelerator.local_process_index}")
- self.device_map = f"cuda:{accelerator.local_process_index}"
- try:
- self.model, self.vision_tower, self.tokenizer, self.image_processor, self.video_token_len = initialize_model(model_path, projection_path, device=self.device)
- except:
- eval_logger.info("Does not find the model from the path you provide, try downloading from the hf repo.")
- model_path = snapshot_download(repo_id=model_path)
- projection_path = os.path.join(snapshot_download(repo_id=projection_path), "video_chatgpt-7B.bin")
- self.model, self.vision_tower, self.tokenizer, self.image_processor, self.video_token_len = initialize_model(model_path, projection_path, device=self.device)
-
- if accelerator.num_processes > 1:
- assert accelerator.distributed_type in [DistributedType.FSDP, DistributedType.MULTI_GPU, DistributedType.DEEPSPEED], "Unsupported distributed type provided. Only DDP and FSDP are supported."
- # If you want to use DistributedType.DEEPSPEED, you have to run accelerate config before using the model
- # Also, you have to select zero stage 0 (equivalent to DDP) in order to make the prepare model works
- # I tried to set different parameters in the kwargs to let default zero 2 stage works, but it didn't work.
- if accelerator.distributed_type == DistributedType.DEEPSPEED:
- kwargs = {
- "train_micro_batch_size_per_gpu": self.batch_size_per_gpu,
- "train_batch_size": self.batch_size_per_gpu * accelerator.num_processes,
- }
- AcceleratorState().deepspeed_plugin.deepspeed_config_process(must_match=True, **kwargs)
- eval_logger.info("Detected that you are using DistributedType.DEEPSPEED. Make sure you run `accelerate config` and set zero stage to 0")
- if accelerator.distributed_type == DistributedType.FSDP or accelerator.distributed_type == DistributedType.DEEPSPEED:
- self._model = accelerator.prepare(self.model)
- else:
- self._model = accelerator.prepare_model(self.model, evaluation_mode=True)
- self.accelerator = accelerator
- if self.accelerator.is_local_main_process:
- eval_logger.info(f"Using {accelerator.num_processes} devices with data parallelism")
- self._rank = self.accelerator.local_process_index
- self._world_size = self.accelerator.num_processes
- elif accelerator.num_processes == 1 and device_map == "auto":
- eval_logger.info(f"Using {accelerator.num_processes} devices with tensor parallelism")
- self._rank = 0
- self._word_size = 1
- else:
- eval_logger.info(f"Using single device: {self._device}")
- self.model.to(self._device)
- self._rank = 0
- self._world_size = 1
-
- def flatten(self, input):
- new_list = []
- for i in input:
- for j in i:
- new_list.append(j)
- return new_list
-
- def generate_until(self, requests) -> List[str]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, gen_kwargs, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- # videos = []
- for visual in visuals:
- video_frames = read_video_pyav(visual, num_frm=self.num_frm)
- target_h, target_w = 224, 224
- # If image shape is not as target, resize it
- if video_frames.shape[-3] != target_h or video_frames.shape[-2] != target_w:
- video_frames = torch.from_numpy(video_frames).permute(0, 3, 1, 2).float()
- video_frames = torch.nn.functional.interpolate(video_frames, size=(target_h, target_w))
- video_frames = video_frames.permute(0, 2, 3, 1).to(torch.uint8).numpy()
- video_frames = [Image.fromarray(frame) for frame in video_frames]
- if len(video_frames) > self.num_frm:
- video_frames = video_frames[: self.num_frm]
- # VideoChatGPT load video return a list of PIL Image
- # videos += video_frames
-
- output = video_chatgpt_infer(
- video_frames, contexts, conv_mode="video-chatgpt_v1", model=self.model, vision_tower=self.vision_tower, tokenizer=self.tokenizer, image_processor=self.image_processor, video_token_len=self.video_token_len
- )
-
- res.append(output)
- pbar.update(1)
-
- return res
-
- def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]:
- res = []
- pbar = tqdm(total=len(requests), disable=(self.rank != 0), desc="Model Responding")
-
- for contexts, doc_to_target, doc_to_visual, doc_id, task, split in [reg.args for reg in requests]:
- # encode, pad, and truncate contexts for this batch
- if type(doc_to_target) == str:
- continuation = doc_to_target
- else:
- continuation = doc_to_target(self.task_dict[task][split][doc_id])
- visuals = [doc_to_visual(self.task_dict[task][split][doc_id])]
- visuals = self.flatten(visuals)
- videos = []
- for visual in visuals:
- video_frames = load_video(visual, num_frm=self.num_frm)
- # VideoChatGPT load video return a list of PIL Image
- videos += video_frames
- image_tensor = self.image_processor.preprocess(videos, return_tensors="pt")["pixel_values"]
-
- # Move image tensor to GPU and reduce precision to half
- image_tensor = image_tensor.half().to(self.device)
-
- # Generate video spatio-temporal features
- with torch.no_grad():
- image_forward_outs = self.vision_tower(image_tensor, output_hidden_states=True)
- frame_features = image_forward_outs.hidden_states[-2][:, 1:] # Use second to last layer as in LLaVA
- video_spatio_temporal_features = get_spatio_temporal_features_torch(frame_features).cuda()
-
- outputs, input_ids, context_ids = video_chatgpt_infer_ppl(
- # video_frames,
- contexts,
- continuation,
- conv_mode="video-chatgpt_v1",
- model=self.model,
- vision_tower=self.vision_tower,
- tokenizer=self.tokenizer,
- image_processor=self.image_processor,
- video_token_len=self.video_token_len,
- video_spatio_temporal_features=video_spatio_temporal_features,
- )
-
- loss = outputs["loss"]
- # loss = torch.exp(loss)
- logits = outputs["logits"]
- greedy_tokens = logits.argmax(dim=-1)
- cont_toks = input_ids[:, context_ids.shape[1] :] # [1, seq]
- greedy_tokens = greedy_tokens[:, context_ids.shape[1] : input_ids.shape[1]] # [1, seq]
- max_equal = (greedy_tokens == cont_toks).all()
- res.append((float(loss.item()), bool(max_equal)))
- pbar.update(1)
- pbar.close()
- return res
-
- @property
- def batch_size(self):
- return self.batch_size_per_gpu
-
- @property
- def device(self):
- return self._device
-
- @property
- def rank(self):
- return self._rank
-
- @property
- def world_size(self):
- return self._world_size
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/__init__.py b/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/__init__.py
deleted file mode 100644
index c5f48379d5a1cc244694ecce37626c6160f77abf..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .model import VideoChatGPTLlamaForCausalLM
diff --git a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/constants.py b/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/constants.py
deleted file mode 100644
index c9ea9ac1ec9dcb9a52feec53e35008ca78e298b8..0000000000000000000000000000000000000000
--- a/lmms-eval-0.2.0.post1/lmms_eval/models/video_chatgpt/constants.py
+++ /dev/null
@@ -1,11 +0,0 @@
-CONTROLLER_HEART_BEAT_EXPIRATION = 30
-WORKER_HEART_BEAT_INTERVAL = 15
-
-LOGDIR = "."
-
-
-# Defining model
-DEFAULT_VIDEO_TOKEN = "