diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..d2bcae684a29f2d6a30521962fede95cd3ae95ed 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+assets/cat_and_chicken.mp4 filter=lfs diff=lfs merge=lfs -text
+assets/pipeline.png filter=lfs diff=lfs merge=lfs -text
+assets/sora.mp4 filter=lfs diff=lfs merge=lfs -text
+assets/sora.png filter=lfs diff=lfs merge=lfs -text
+videollama2/serve/examples/1034346401.mp4 filter=lfs diff=lfs merge=lfs -text
+videollama2/serve/examples/sample_demo_1.mp4 filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..5d2b4c1ab07337c2106b40a88610bf991e0707aa
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,58 @@
+# Python
+__pycache__
+*.pyc
+*.egg-info
+dist
+
+# Log
+*.log
+*.log.*
+*.json
+*.jsonl
+log_dir*/
+temp*/
+
+# Data
+!**/alpaca-data-conversation.json
+
+# Editor
+.idea
+*.swp
+
+# Other
+.DS_Store
+3rd_parties
+
+# jupyter
+.ipynb_checkpoints
+*.ipynb
+
+# DevContainer
+!.devcontainer/*
+
+# Demo
+serve_images/
+temp/
+
+# data folder
+data/
+dataset/
+datasets/
+
+# training folder
+wandb
+ckpts*
+output
+output/
+checkpoints
+checkpoints/
+work_dirs*/
+
+# evaluation folder
+/eval
+/eval*
+
+# pretrained weights
+pretrained/
+publish_models/
+public_models/
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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/README.md b/README.md
index 4b0aafea535a24b7e1ee3b5c903b64d76985fd7d..b6975ca5b29dd8039a49f6db66a468424840bf65 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,345 @@
---
-title: Verblaze
-emoji: π
-colorFrom: red
-colorTo: yellow
+title: verblaze
+app_file: videollama2/serve/gradio_web_server.py
sdk: gradio
-sdk_version: 4.44.0
-app_file: app.py
-pinned: false
+sdk_version: 3.50.0
---
+
+
+
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
+
+ If our project helps you, please give us a star β on GitHub to support us. ππ
+
+
+
+[![hf_space](https://img.shields.io/badge/π€-Demo-9C276A.svg)](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2)
+[![hf_checkpoint](https://img.shields.io/badge/π€-Checkpoints-9C276A.svg)](https://huggingface.co/collections/DAMO-NLP-SG/videollama-2-6669b6b6f0493188305c87ed)
+[![hf_data](https://img.shields.io/badge/π€-MSVC-9C276A.svg)](https://huggingface.co/datasets/DAMO-NLP-SG/Multi-Source-Video-Captioning)
+[![arXiv](https://img.shields.io/badge/Arxiv-2406.07476-AD1C18.svg?logo=arXiv)](https://arxiv.org/abs/2406.07476)
+[![License](https://img.shields.io/badge/License-Apache%202.0-yellow)](https://github.com/DAMO-NLP-SG/VideoLLaMA2/blob/main/LICENSE)
+[![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2FDAMO-NLP-SG%2FVideoLLaMA2&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=Visitor&edge_flat=false)](https://hits.seeyoufarm.com)
+[![GitHub issues](https://img.shields.io/github/issues/DAMO-NLP-SG/VideoLLaMA2?color=critical&label=Issues)](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aopen+is%3Aissue)
+[![GitHub closed issues](https://img.shields.io/github/issues-closed/DAMO-NLP-SG/VideoLLaMA2?color=success&label=Issues)](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aissue+is%3Aclosed)
+
+
+
+[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/videollama-2-advancing-spatial-temporal/zero-shot-video-question-answer-on-egoschema-1)](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-egoschema-1?p=videollama-2-advancing-spatial-temporal)
+[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/videollama-2-advancing-spatial-temporal/video-question-answering-on-perception-test)](https://paperswithcode.com/sota/video-question-answering-on-perception-test?p=videollama-2-advancing-spatial-temporal)
+[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/videollama-2-advancing-spatial-temporal/video-question-answering-on-mvbench)](https://paperswithcode.com/sota/video-question-answering-on-mvbench?p=videollama-2-advancing-spatial-temporal)
+[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/videollama-2-advancing-spatial-temporal/zero-shot-video-question-answer-on-video-mme-1)](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-video-mme-1?p=videollama-2-advancing-spatial-temporal)
+[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/videollama-2-advancing-spatial-temporal/zero-shot-video-question-answer-on-video-mme)](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-video-mme?p=videollama-2-advancing-spatial-temporal)
+
+π‘ Some other multimodal-LLM projects from our team may interest you β¨.
+
+
+> [**Video-LLaMA: An Instruction-tuned Audio-Visual Language Model for Video Understanding**](https://github.com/DAMO-NLP-SG/Video-LLaMA)
+> Hang Zhang, Xin Li, Lidong Bing
+[![github](https://img.shields.io/badge/-Github-black?logo=github)](https://github.com/DAMO-NLP-SG/Video-LLaMA) [![github](https://img.shields.io/github/stars/DAMO-NLP-SG/Video-LLaMA.svg?style=social)](https://github.com/DAMO-NLP-SG/Video-LLaMA) [![arXiv](https://img.shields.io/badge/Arxiv-2306.02858-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2306.02858)
+
+> [**VCD: Mitigating Object Hallucinations in Large Vision-Language Models through Visual Contrastive Decoding**](https://arxiv.org/abs/2311.16922)
+> Sicong Leng, Hang Zhang, Guanzheng Chen, Xin Li, Shijian Lu, Chunyan Miao, Lidong Bing
+[![github](https://img.shields.io/badge/-Github-black?logo=github)](https://github.com/DAMO-NLP-SG/VCD) [![github](https://img.shields.io/github/stars/DAMO-NLP-SG/VCD.svg?style=social)](https://github.com/DAMO-NLP-SG/VCD) [![arXiv](https://img.shields.io/badge/Arxiv-2311.16922-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2311.16922)
+
+
+
+
+
+
+## π° News
+* **[2024.08.14]** Release checkpoints of [VideoLLaMA2-72B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B-Base) and [VideoLLaMA2-72B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B)
+* **[2024.07.30]** Release checkpoints of [VideoLLaMA2-8x7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B-Base) and [VideoLLaMA2-8x7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B).
+* **[2024.06.25]** π₯π₯ As of Jun 25, our [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) is the **Top-1** ~7B-sized VideoLLM on the [MLVU Leaderboard](https://github.com/JUNJIE99/MLVU?tab=readme-ov-file#trophy-mini-leaderboard).
+* **[2024.06.18]** π₯π₯ As of Jun 18, our [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) is the **Top-1** ~7B-sized VideoLLM on the [VideoMME Leaderboard](https://video-mme.github.io/home_page.html#leaderboard).
+* **[2024.06.17]** ππ Update technical report with the latest results and the missing references. If you have works closely related to VideoLLaMA 2 but not mentioned in the paper, feel free to let us know.
+* **[2024.06.14]** π₯π₯ [Online Demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2) is available.
+* **[2024.06.03]** Release training, evaluation, and serving codes of VideoLLaMA 2.
+
+
+
+
+## π οΈ Requirements and Installation
+Basic Dependencies:
+* Python >= 3.8
+* Pytorch >= 2.2.0
+* CUDA Version >= 11.8
+* transformers == 4.40.0 (for reproducing paper results)
+* tokenizers == 0.19.1
+
+**[Online Mode]** Install required packages (better for development):
+```bash
+git clone https://github.com/DAMO-NLP-SG/VideoLLaMA2
+cd VideoLLaMA2
+pip install -r requirements.txt
+pip install flash-attn==2.5.8 --no-build-isolation
+```
+
+**[Offline Mode]** Install VideoLLaMA2 as a Python package (better for direct use):
+```bash
+git clone https://github.com/DAMO-NLP-SG/VideoLLaMA2
+cd VideoLLaMA2
+pip install --upgrade pip # enable PEP 660 support
+pip install -e .
+pip install flash-attn==2.5.8 --no-build-isolation
+```
+
+## π Main Results
+
+### Multi-Choice Video QA & Video Captioning
+
+
+### Open-Ended Video QA
+
+
+
+
+## :earth_americas: Model Zoo
+| Model Name | Model Type | Visual Encoder | Language Decoder | # Training Frames |
+|:----------------|:------------:|:----------------|:------------------|:----------------:|
+| [VideoLLaMA2-7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 8 |
+| [VideoLLaMA2-7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 8 |
+| [VideoLLaMA2-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 16 |
+| [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 16 |
+| [VideoLLaMA2-8x7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | 8 |
+| [VideoLLaMA2-8x7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | 8 |
+| [VideoLLaMA2-72B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Qwen2-72B-Instruct](https://huggingface.co/Qwen/Qwen2-72B-Instruct) | 8 |
+| [VideoLLaMA2-72B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Qwen2-72B-Instruct](https://huggingface.co/Qwen/Qwen2-72B-Instruct) | 8 |
+
+
+## [π€ Demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2)
+
+It is highly recommended to try our [online demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2) first.
+
+To run a video-based LLM (Large Language Model) web demonstration on your device, you will first need to ensure that you have the necessary model checkpoints prepared, followed by adhering to the steps outlined to successfully launch the demo.
+
+### Single-model Version
+
+* Launch a gradio app directly ([VideoLLaMA2-7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B) is adopted by default):
+```bash
+python videollama2/serve/gradio_web_server_adhoc.py
+```
+
+### Multi-model Version
+
+1. Launch a global controller
+```bash
+cd /path/to/VideoLLaMA2
+python -m videollama2.serve.controller --host 0.0.0.0 --port 10000
+```
+
+2. Launch a gradio webserver
+```bash
+python -m videollama2.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
+```
+
+3. Launch one or multiple model workers
+```bash
+# export HF_ENDPOINT=https://hf-mirror.com # If you are unable to access Hugging Face, try to uncomment this line.
+python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path /PATH/TO/MODEL1
+python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40001 --worker http://localhost:40001 --model-path /PATH/TO/MODEL2
+python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40002 --worker http://localhost:40002 --model-path /PATH/TO/MODEL3
+...
+```
+
+
+## ποΈ Training & Evaluation
+
+### Quick Start
+
+To facilitate further development on top of our codebase, we provide a quick-start guide on how to train a customized [VideoLLaMA2](https://github.com/DAMO-NLP-SG/VideoLLaMA2) with [VideoLLaVA](https://github.com/PKU-YuanGroup/Video-LLaVA) dataset and evaluate the trained model on the mainstream video-llm benchmarks.
+
+1. Training Data Structure:
+```bash
+VideoLLaMA2
+βββ datasets
+β βββ videollava_pt
+| | βββ llava_image/ # Available at: https://pan.baidu.com/s/17GYcE69FcJjjUM0e4Gad2w?pwd=9ga3 or https://drive.google.com/drive/folders/1QmFj2FcMAoWNCUyiUtdcW0-IOhLbOBcf?usp=drive_link
+| | βββ valley/ # Available at: https://pan.baidu.com/s/1jluOimE7mmihEBfnpwwCew?pwd=jyjz or https://drive.google.com/drive/folders/1QmFj2FcMAoWNCUyiUtdcW0-IOhLbOBcf?usp=drive_link
+| | βββ valley_llavaimage.json # Available at: https://drive.google.com/file/d/1zGRyVSUMoczGq6cjQFmT0prH67bu2wXD/view, including 703K video-text and 558K image-text pairs
+β βββ videollava_sft
+| | βββ llava_image_tune/ # Available at: https://pan.baidu.com/s/1l-jT6t_DlN5DTklwArsqGw?pwd=o6ko
+| | βββ videochatgpt_tune/ # Available at: https://pan.baidu.com/s/10hJ_U7wVmYTUo75YHc_n8g?pwd=g1hf
+| | βββ videochatgpt_llavaimage_tune.json # Available at: https://drive.google.com/file/d/1zGRyVSUMoczGq6cjQFmT0prH67bu2wXD/view, including 100K video-centric, 625K image-centric and 40K text-only conversations
+```
+2. Command:
+```bash
+# VideoLLaMA2-vllava pretraining
+bash scripts/vllava/pretrain.sh
+# VideoLLaMA2-vllava finetuning
+bash scripts/vllava/finetune.sh
+```
+3. Evaluation Data Structure:
+```bash
+VideoLLaMA2
+βββ eval
+β βββ egoschema # Official website: https://github.com/egoschema/EgoSchema
+| | βββ good_clips_git/ # Available at: https://drive.google.com/drive/folders/1SS0VVz8rML1e5gWq7D7VtP1oxE2UtmhQ
+| | βββ questions.json # Available at: https://github.com/egoschema/EgoSchema/blob/main/questions.json
+β βββ mvbench # Official website: https://huggingface.co/datasets/OpenGVLab/MVBench
+| | βββ video/
+| | | βββ clever/
+| | | βββ ...
+| | βββ json/
+| | | βββ action_antonym.json
+| | | βββ ...
+β βββ perception_test_mcqa # Official website: https://huggingface.co/datasets/OpenGVLab/MVBench
+| | βββ videos/ # Available at: https://storage.googleapis.com/dm-perception-test/zip_data/test_videos.zip
+| | βββ mc_question_test.json # Download from https://storage.googleapis.com/dm-perception-test/zip_data/mc_question_test_annotations.zip
+β βββ videomme # Official website: https://video-mme.github.io/home_page.html#leaderboard
+| | βββ test-00000-of-00001.parquet
+| | βββ videos/
+| | βββ subtitles/
+β βββ Activitynet_Zero_Shot_QA # Official website: https://github.com/MILVLG/activitynet-qa
+| | βββ all_test/ # Available at: https://mbzuaiac-my.sharepoint.com/:u:/g/personal/hanoona_bangalath_mbzuai_ac_ae/EatOpE7j68tLm2XAd0u6b8ABGGdVAwLMN6rqlDGM_DwhVA?e=90WIuW
+| | βββ test_q.json # Available at: https://github.com/MILVLG/activitynet-qa/tree/master/dataset
+| | βββ test_a.json # Available at: https://github.com/MILVLG/activitynet-qa/tree/master/dataset
+β βββ MSVD_Zero_Shot_QA # Official website: https://github.com/xudejing/video-question-answering
+| | βββ videos/
+| | βββ test_q.json
+| | βββ test_a.json
+β βββ videochatgpt_gen # Official website: https://github.com/mbzuai-oryx/Video-ChatGPT/tree/main/quantitative_evaluation
+| | βββ Test_Videos/ # Available at: https://mbzuaiac-my.sharepoint.com/:u:/g/personal/hanoona_bangalath_mbzuai_ac_ae/EatOpE7j68tLm2XAd0u6b8ABGGdVAwLMN6rqlDGM_DwhVA?e=90WIuW
+| | βββ Test_Human_Annotated_Captions/ # Available at: https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking%2FTest%5FHuman%5FAnnotated%5FCaptions%2Ezip&parent=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking&ga=1
+| | βββ generic_qa.json # These three json files available at: https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking%2FBenchmarking%5FQA&ga=1
+| | βββ temporal_qa.json
+| | βββ consistency_qa.json
+```
+4. Command:
+```bash
+# mvbench evaluation
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/eval/eval_video_qa_mvbench.sh
+# activitynet-qa evaluation (need to set azure openai key/endpoint/deployname)
+CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/eval/eval_video_qa_mvbench.sh
+```
+
+### Data Format
+
+If you want to train a video-llm on your data, you need to follow the procedures below to prepare the video/image sft data:
+
+1. Suppose your data structure is like:
+```bash
+VideoLLaMA2
+βββ datasets
+β βββ custom_sft
+β | βββ images
+β | βββ videos
+| | βββ custom.json
+```
+2. Then you should re-organize the annotated video/image sft data according to the following format:
+```json
+[
+ {
+ "id": 0,
+ "video": "images/xxx.jpg",
+ "conversations": [
+ {
+ "from": "human",
+ "value": "\nWhat are the colors of the bus in the image?"
+ },
+ {
+ "from": "gpt",
+ "value": "The bus in the image is white and red."
+ },
+ ...
+ ],
+ }
+ {
+ "id": 1,
+ "video": "videos/xxx.mp4",
+ "conversations": [
+ {
+ "from": "human",
+ "value": "\nWhat are the main activities that take place in the video?"
+ },
+ {
+ "from": "gpt",
+ "value": "The main activities that take place in the video are the preparation of camera equipment by a man, a group of men riding a helicopter, and a man sailing a boat through the water."
+ },
+ ...
+ ],
+ },
+ ...
+]
+```
+3. Modify the `scripts/custom/finetune.sh`:
+```bash
+...
+--data_path datasets/custom_sft/custom.json
+--data_folder datasets/custom_sft/
+--pretrain_mm_mlp_adapter CONNECTOR_DOWNLOAD_PATH (e.g., DAMO-NLP-SG/VideoLLaMA2-7B-Base)
+...
+```
+
+## π€ Inference
+
+Video/Image Inference:
+```python
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+
+def inference():
+ disable_torch_init()
+
+ # Video Inference
+ modal = 'video'
+ modal_path = 'assets/cat_and_chicken.mp4'
+ instruct = 'What animals are in the video, what are they doing, and how does the video feel?'
+ # Reply:
+ # The video features a kitten and a baby chick playing together. The kitten is seen laying on the floor while the baby chick hops around. The two animals interact playfully with each other, and the video has a cute and heartwarming feel to it.
+
+ # Image Inference
+ modal = 'image'
+ modal_path = 'assets/sora.png'
+ instruct = 'What is the woman wearing, what is she doing, and how does the image feel?'
+ # Reply:
+ # The woman in the image is wearing a black coat and sunglasses, and she is walking down a rain-soaked city street. The image feels vibrant and lively, with the bright city lights reflecting off the wet pavement, creating a visually appealing atmosphere. The woman's presence adds a sense of style and confidence to the scene, as she navigates the bustling urban environment.
+
+ model_path = 'DAMO-NLP-SG/VideoLLaMA2-7B'
+ # Base model inference (only need to replace model_path)
+ # model_path = 'DAMO-NLP-SG/VideoLLaMA2-7B-Base'
+ model, processor, tokenizer = model_init(model_path)
+ output = mm_infer(processor[modal](modal_path), instruct, model=model, tokenizer=tokenizer, do_sample=False, modal=modal)
+
+ print(output)
+
+if __name__ == "__main__":
+ inference()
+```
+
+## π Citation
+
+If you find VideoLLaMA useful for your research and applications, please cite using this BibTeX:
+```bibtex
+@article{damonlpsg2024videollama2,
+ title={VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs},
+ author={Cheng, Zesen and Leng, Sicong and Zhang, Hang and Xin, Yifei and Li, Xin and Chen, Guanzheng and Zhu, Yongxin and Zhang, Wenqi and Luo, Ziyang and Zhao, Deli and Bing, Lidong},
+ journal={arXiv preprint arXiv:2406.07476},
+ year={2024},
+ url = {https://arxiv.org/abs/2406.07476}
+}
+
+@article{damonlpsg2023videollama,
+ title = {Video-LLaMA: An Instruction-tuned Audio-Visual Language Model for Video Understanding},
+ author = {Zhang, Hang and Li, Xin and Bing, Lidong},
+ journal = {arXiv preprint arXiv:2306.02858},
+ year = {2023},
+ url = {https://arxiv.org/abs/2306.02858}
+}
+```
+
+## π Acknowledgement
+The codebase of VideoLLaMA 2 is adapted from [**LLaVA 1.5**](https:github.com/haotian-liu/LLaVA) and [**FastChat**](https://github.com/lm-sys/FastChat). We are also grateful for the following projects our VideoLLaMA 2 arise from:
+* [**LLaMA 2**](https://github.com/meta-llama/llama), [**Mistral-7B**](https://mistral.ai/news/announcing-mistral-7b/), [**OpenAI CLIP**](https://openai.com/index/clip/), [**Honeybee**](https://github.com/kakaobrain/honeybee).
+* [**Video-ChatGPT**](https://github.com/mbzuai-oryx/Video-ChatGPT), [**Video-LLaVA**](https://github.com/PKU-YuanGroup/Video-LLaVA).
+* [**WebVid**](https://github.com/m-bain/webvid), [**Panda-70M**](https://github.com/snap-research/Panda-70M), [**LanguageBind**](https://github.com/PKU-YuanGroup/LanguageBind), [**InternVid**](https://github.com/OpenGVLab/InternVideo/tree/main/Data/InternVid).
+* [**VideoChat2**](https://github.com/OpenGVLab/Ask-Anything/tree/main/video_chat2), [**Valley**](https://github.com/RupertLuo/Valley), [**VTimeLLM**](https://github.com/huangb23/VTimeLLM), [**ShareGPT4V**](https://sharegpt4v.github.io/).
+
+
+## π License
+
+This project is released under the Apache 2.0 license as found in the LICENSE file.
+The service is a research preview intended for **non-commercial use ONLY**, subject to the model Licenses of LLaMA and Mistral, Terms of Use of the data generated by OpenAI, and Privacy Practices of ShareGPT. Please get in touch with us if you find any potential violations.
diff --git a/assets/cat_and_chicken.mp4 b/assets/cat_and_chicken.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..e5898c862833c17ffbce625736fc6614fb14fe7c
--- /dev/null
+++ b/assets/cat_and_chicken.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1f24723064ee27ea8fc7a30b4542601ed03a42952c0d20fe918213cf876bfec4
+size 18956323
diff --git a/assets/logo.png b/assets/logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..8bf0cad2edb6c6db5df4011fcc7660d736f00e31
Binary files /dev/null and b/assets/logo.png differ
diff --git a/assets/pipeline.png b/assets/pipeline.png
new file mode 100644
index 0000000000000000000000000000000000000000..29f32809e0e7744a07de4b00602a67549673f333
--- /dev/null
+++ b/assets/pipeline.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:eeab6d9f13787337b40399427e419506f49b55a4fb4fe40ba91e25618d03eeb0
+size 4375052
diff --git a/assets/sora.mp4 b/assets/sora.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..61d726eac64b06fe969c9d4b105303b8c0eeb88e
--- /dev/null
+++ b/assets/sora.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:24e5f0ea3353f23225d00efcdf136fa6dc346301fc34082790e2152c80fa0490
+size 14978533
diff --git a/assets/sora.png b/assets/sora.png
new file mode 100644
index 0000000000000000000000000000000000000000..b1619da272d6caab2c128c62c4c05f3b143c43bb
--- /dev/null
+++ b/assets/sora.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6b69de5c87b429c7b1a87de6f9cb3f5ec6aec5f58ab6ab7c0f727a5d0ec259a5
+size 1051277
diff --git a/aws/README.md b/aws/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..f92add4ec2a38f25f333cd4eca75cdda51627cdd
--- /dev/null
+++ b/aws/README.md
@@ -0,0 +1,54 @@
+# AWS CLI v2
+
+This bundle contains a built executable of the AWS CLI v2.
+
+## Installation
+
+To install the AWS CLI v2, run the `install` script:
+```
+$ sudo ./install
+You can now run: /usr/local/bin/aws --version
+```
+This will install the AWS CLI v2 at `/usr/local/bin/aws`. Assuming
+`/usr/local/bin` is on your `PATH`, you can now run:
+```
+$ aws --version
+```
+
+
+### Installing without sudo
+
+If you don't have ``sudo`` permissions or want to install the AWS
+CLI v2 only for the current user, run the `install` script with the `-b`
+and `-i` options:
+```
+$ ./install -i ~/.local/aws-cli -b ~/.local/bin
+```
+This will install the AWS CLI v2 in `~/.local/aws-cli` and create
+symlinks for `aws` and `aws_completer` in `~/.local/bin`. For more
+information about these options, run the `install` script with `-h`:
+```
+$ ./install -h
+```
+
+### Updating
+
+If you run the `install` script and there is a previously installed version
+of the AWS CLI v2, the script will error out. To update to the version included
+in this bundle, run the `install` script with `--update`:
+```
+$ sudo ./install --update
+```
+
+
+### Removing the installation
+
+To remove the AWS CLI v2, delete the its installation and symlinks:
+```
+$ sudo rm -rf /usr/local/aws-cli
+$ sudo rm /usr/local/bin/aws
+$ sudo rm /usr/local/bin/aws_completer
+```
+Note if you installed the AWS CLI v2 using the `-b` or `-i` options, you will
+need to remove the installation and the symlinks in the directories you
+specified.
diff --git a/aws/THIRD_PARTY_LICENSES b/aws/THIRD_PARTY_LICENSES
new file mode 100644
index 0000000000000000000000000000000000000000..d6680435d0dedd556a48aae56d01d3e499e8b0fe
--- /dev/null
+++ b/aws/THIRD_PARTY_LICENSES
@@ -0,0 +1,1468 @@
+** cryptography 3.3.2; version 3.3.2 --
+https://github.com/pyca/cryptography/tree/3.3.2
+Copyright (c) Individual contributors.
+All rights reserved.
+
+This software is made available under the terms of *either* of the licenses
+found in LICENSE.APACHE or LICENSE.BSD. Contributions to cryptography are made
+under the terms of *both* these licenses.
+
+The code used in the OpenSSL locking callback and OS random engine is derived
+from CPython, and is licensed under the terms of the PSF License Agreement.
+
+* For cryptography 3.3.2 see also this required NOTICE:
+ Copyright (c) Individual contributors.
+ All rights reserved.
+
+------
+
+** botocore; version 2 -- https://github.com/boto/botocore/tree/v2
+Botocore
+Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+----
+
+Botocore includes a vendorized copy of the requests python library to ease
+installation.
+
+Requests License
+================
+
+Copyright 2013 Kenneth Reitz
+
+ 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.
+
+
+The requests library also includes some vendorized python libraries to ease
+installation.
+
+Urllib3 License
+===============
+
+This is the MIT license: http://www.opensource.org/licenses/mit-license.php
+
+Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt),
+Modifications copyright 2012 Kenneth Reitz.
+
+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.
+
+Chardet License
+===============
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Bundle of CA Root Certificates
+==============================
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+02110-1301
+** s3transfer; version 0 -- https://github.com/boto/s3transfer
+s3transfer
+Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+Apache License
+
+Version 2.0, January 2004
+
+http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND
+DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction, and
+ distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by the
+ copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all other
+ entities that control, are controlled by, or are under common control
+ with that entity. For the purposes of this definition, "control" means
+ (i) the power, direct or indirect, to cause the direction or management
+ of such entity, whether by contract or otherwise, or (ii) ownership of
+ fifty percent (50%) or more of the outstanding shares, or (iii)
+ beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
+ permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation source,
+ and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but not limited
+ to compiled object code, generated documentation, and conversions to
+ other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or Object
+ form, made available under the License, as indicated by a copyright
+ notice that is included in or attached to the work (an example is
+ provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object form,
+ that is based on (or derived from) the Work and for which the editorial
+ revisions, annotations, elaborations, or other modifications represent,
+ as a whole, an original work of authorship. For the purposes of this
+ License, Derivative Works shall not include works that remain separable
+ from, or merely link (or bind by name) to the interfaces of, the Work and
+ Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including the original
+ version of the Work and any modifications or additions to that Work or
+ Derivative Works thereof, that is intentionally submitted to Licensor for
+ inclusion in the Work by the copyright owner or by an individual or Legal
+ Entity authorized to submit on behalf of the copyright owner. For the
+ purposes of this definition, "submitted" means any form of electronic,
+ verbal, or written communication sent to the Licensor or its
+ representatives, including but not limited to communication on electronic
+ mailing lists, source code control systems, and issue tracking systems
+ that are managed by, or on behalf of, the Licensor for the purpose of
+ discussing and improving the Work, but excluding communication that is
+ conspicuously marked or otherwise designated in writing by the copyright
+ owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
+ behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
+ License, each Contributor hereby grants to You a perpetual, worldwide,
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
+ sublicense, and distribute the Work and such Derivative Works in Source or
+ Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of this
+ License, each Contributor hereby grants to You a perpetual, worldwide,
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
+ this section) patent license to make, have made, use, offer to sell, sell,
+ import, and otherwise transfer the Work, where such license applies only to
+ those patent claims licensable by such Contributor that are necessarily
+ infringed by their Contribution(s) alone or by combination of their
+ Contribution(s) with the Work to which such Contribution(s) was submitted.
+ If You institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+ Contribution incorporated within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under this
+ License for that Work shall terminate as of the date such litigation is
+ filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
+ Derivative Works thereof in any medium, with or without modifications, and
+ in Source or Object form, provided that You meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative Works a
+ copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices stating
+ that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works that You
+ distribute, all copyright, patent, trademark, and attribution notices
+ from the Source form of the Work, excluding those notices that do not
+ pertain to any part of the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must include
+ a readable copy of the attribution notices contained within such NOTICE
+ file, excluding those notices that do not pertain to any part of the
+ Derivative Works, in at least one of the following places: within a
+ NOTICE text file distributed as part of the Derivative Works; within the
+ Source form or documentation, if provided along with the Derivative
+ Works; or, within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents of the
+ NOTICE file are for informational purposes only and do not modify the
+ License. You may add Your own attribution notices within Derivative Works
+ that You distribute, alongside or as an addendum to the NOTICE text from
+ the Work, provided that such additional attribution notices cannot be
+ construed as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and may
+ provide additional or different license terms and conditions for use,
+ reproduction, or distribution of Your modifications, or for any such
+ Derivative Works as a whole, provided Your use, reproduction, and
+ distribution of the Work otherwise complies with the conditions stated in
+ this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
+ Contribution intentionally submitted for inclusion in the Work by You to the
+ Licensor shall be under the terms and conditions of this License, without
+ any additional terms or conditions. Notwithstanding the above, nothing
+ herein shall supersede or modify the terms of any separate license agreement
+ you may have executed with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor, except
+ as required for reasonable and customary use in describing the origin of the
+ Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
+ writing, Licensor provides the Work (and each Contributor provides its
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied, including, without limitation, any
+ warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
+ FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining
+ the appropriateness of using or redistributing the Work and assume any risks
+ associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory, whether
+ in tort (including negligence), contract, or otherwise, unless required by
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
+ in writing, shall any Contributor be liable to You for damages, including
+ any direct, indirect, special, incidental, or consequential damages of any
+ character arising as a result of this License or out of the use or inability
+ to use the Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all other
+ commercial damages or losses), even if such Contributor has been advised of
+ the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work
+ or Derivative Works thereof, You may choose to offer, and charge a fee for,
+ acceptance of support, warranty, indemnity, or other liability obligations
+ and/or rights consistent with this License. However, in accepting such
+ obligations, You may act only on Your own behalf and on Your sole
+ responsibility, not on behalf of any other Contributor, and only if You
+ agree to indemnify, defend, and hold each Contributor harmless for any
+ liability incurred by, or claims asserted against, such Contributor by
+ reason of your accepting any such warranty or additional liability. END OF
+ TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification
+within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+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.
+
+* For botocore see also this required NOTICE:
+ Botocore
+ Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights
+ Reserved.
+
+ ----
+
+ Botocore includes a vendorized copy of the requests python library to ease
+ installation.
+
+ Requests License
+ ================
+
+ Copyright 2013 Kenneth Reitz
+
+ 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.
+
+
+ The requests library also includes some vendorized python libraries to ease
+ installation.
+
+ Urllib3 License
+ ===============
+
+ This is the MIT license: http://www.opensource.org/licenses/mit-license.php
+
+ Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt),
+ Modifications copyright 2012 Kenneth Reitz.
+
+ 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.
+
+ Chardet License
+ ===============
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301 USA
+
+ Bundle of CA Root Certificates
+ ==============================
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301
+* For s3transfer see also this required NOTICE:
+ s3transfer
+ Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+------
+
+** colorama; version 0.4.2 -- https://pypi.org/project/colorama/
+Copyright (c) 2010 Jonathan Hartley
+All rights reserved.
+
+Copyright (c) 2010 Jonathan Hartley
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holders, nor those of its contributors
+ may be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------
+
+** prompt-toolkit; version 2.0.10 --
+https://github.com/prompt-toolkit/python-prompt-toolkit/tree/2.0.10
+Copyright (c) 2014, Jonathan Slenders
+All rights reserved.
+
+Copyright (c) 2014, Jonathan Slenders
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+
+* Neither the name of the {organization} nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------
+
+** dateutil; version 2.8.0 -- https://github.com/dateutil/dateutil/tree/2.8.0
+Copyright 2017- Paul Ganssle
+Copyright 2017- dateutil contributors (see AUTHORS file)
+
+Copyright 2017- Paul Ganssle
+Copyright 2017- dateutil contributors (see AUTHORS file)
+
+ 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.
+
+The above license applies to all contributions after 2017-12-01, as well as
+all contributions that have been re-licensed (see AUTHORS file for the list of
+contributors who have re-licensed their code).
+--------------------------------------------------------------------------------
+dateutil - Extensions to the standard Python datetime module.
+
+Copyright (c) 2003-2011 - Gustavo Niemeyer
+Copyright (c) 2012-2014 - Tomi PievilΓ€inen
+Copyright (c) 2014-2016 - Yaron de Leeuw
+Copyright (c) 2015- - Paul Ganssle
+Copyright (c) 2015- - dateutil contributors (see AUTHORS file)
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+The above BSD License Applies to all code, even that also covered by Apache
+2.0.
+
+------
+
+** Pyintaller 3.5; version 3.5 --
+https://github.com/pyinstaller/pyinstaller/tree/v3.5
+Copyright (c) 2010-2020, PyInstaller Development Team
+Copyright (c) 2005-2009, Giovanni Bajo
+Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc.
+
+ * Package Pyintaller 3.5's source code may be found at:
+ https://files.pythonhosted.org/packages/e2/c9/0b44b2ea87ba36395483a672fddd07e6a9cb2b8d3c4a28d7ae76c7e7e1e5/PyInstaller-3.5.tar.gz
+
+================================
+ The PyInstaller licensing terms
+================================
+
+
+Copyright (c) 2010-2020, PyInstaller Development Team
+Copyright (c) 2005-2009, Giovanni Bajo
+Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc.
+
+
+PyInstaller is licensed under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2 of the License,
+or (at your option) any later version.
+
+
+Bootloader Exception
+--------------------
+
+In addition to the permissions in the GNU General Public License, the
+authors give you unlimited permission to link or embed compiled bootloader
+and related files into combinations with other programs, and to distribute
+those combinations without any restriction coming from the use of those
+files. (The General Public License restrictions do apply in other respects;
+for example, they cover modification of the files, and distribution when
+not linked into a combined executable.)
+
+
+Bootloader and Related Files
+----------------------------
+
+Bootloader and related files are files which are embedded within the
+final executable. This includes files in directories:
+
+./bootloader/
+./PyInstaller/loader
+
+
+About the PyInstaller Development Team
+--------------------------------------
+
+The PyInstaller Development Team is the set of contributors
+to the PyInstaller project. A full list with details is kept
+in the documentation directory, in the file
+``doc/CREDITS.rst``.
+
+The core team that coordinates development on GitHub can be found here:
+https://github.com/pyinstaller/pyinstaller. As of 2015, it consists of:
+
+* Hartmut Goebel
+* Martin Zibricky
+* David Vierra
+* David Cortesi
+
+
+Our Copyright Policy
+--------------------
+
+PyInstaller uses a shared copyright model. Each contributor maintains copyright
+over their contributions to PyInstaller. But, it is important to note that
+these
+contributions are typically only changes to the repositories. Thus,
+the PyInstaller source code, in its entirety is not the copyright of any single
+person or institution. Instead, it is the collective copyright of the entire
+PyInstaller Development Team. If individual contributors want to maintain
+a record of what changes/contributions they have specific copyright on, they
+should indicate their copyright in the commit message of the change, when they
+commit the change to the PyInstaller repository.
+
+With this in mind, the following banner should be used in any source code file
+to indicate the copyright and license terms:
+
+
+#-----------------------------------------------------------------------------
+# Copyright (c) 2005-2020, PyInstaller Development Team.
+#
+# Distributed under the terms of the GNU General Public License (version 2
+# or later) with exception for distributing the bootloader.
+#
+# The full license is in the file COPYING.txt, distributed with this software.
+#
+# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
+#-----------------------------------------------------------------------------
+
+
+
+GNU General Public License
+--------------------------
+
+https://gnu.org/licenses/gpl-2.0.html
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+------
+
+** six; version 1.14.0 -- https://github.com/benjaminp/six/tree/1.14.0
+Copyright (c) 2010-2020 Benjamin Peterson
+
+Copyright (c) 2010-2020 Benjamin Peterson
+
+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.
+
+------
+
+** urllib3; version 1.25.8 -- https://github.com/urllib3/urllib3/tree/1.25.8
+Copyright (c) 2008-2019 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
+
+MIT License
+
+Copyright (c) 2008-2019 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
+
+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.
+
+------
+
+** setuptools; version 45.2.0 --
+https://github.com/pypa/setuptools/tree/v45.2.0
+Copyright (C) 2016 Jason R Coombs
+
+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.
+
+------
+
+** wcwidth; version 0.1.8 -- https://github.com/jquast/wcwidth/tree/0.1.8
+Copyright (c) 2014 Jeff Quast
+
+The MIT License (MIT)
+
+Copyright (c) 2014 Jeff Quast
+
+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.
+
+------
+
+** cffi; version 1.14.0 --
+https://foss.heptapod.net/pypy/cffi/tree/branch/release-1.14
+Β© Copyright 2012-2018, Armin Rigo, Maciej Fijalkowski
+
+Except when otherwise stated (look for LICENSE files in directories or
+information at the beginning of each file) all software and
+documentation is licensed as follows:
+
+ The MIT License
+
+ 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.
+
+------
+
+** jmespath; version 0.9.4 --
+https://github.com/jmespath/jmespath.py/tree/0.9.4
+Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
+
+Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
+
+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, dis-
+tribute, sublicense, and/or sell copies of the Software, and to permit
+persons to whom the Software is furnished to do so, subject to the fol-
+lowing 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 MERCHANTABIL-
+ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHOR 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.
+
+------
+
+** ruamel.yaml; version 0.15.100 --
+https://sourceforge.net/p/ruamel-yaml/code/ci/default/tree/
+Copyright (c) 2014-2019 Anthon van der Neut, Ruamel bvba
+
+ The MIT License (MIT)
+
+ Copyright (c) 2014-2020 Anthon van der Neut, Ruamel bvba
+
+ 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.
+
+------
+
+** OpenSSL; version 1.0.2s --
+https://github.com/openssl/openssl/tree/OpenSSL_1_0_1s
+Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.
+Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+
+LICENSE ISSUES
+ ==============
+
+ The OpenSSL toolkit stays under a double license, i.e. both the conditions of
+ the OpenSSL License and the original SSLeay license apply to the toolkit.
+ See below for the actual license texts.
+
+ OpenSSL License
+ ---------------
+
+/* ====================================================================
+ * Copyright (c) 1998-2017 The OpenSSL Project. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * openssl-core@openssl.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
+ * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+ Original SSLeay License
+ -----------------------
+
+/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+ * All rights reserved.
+ *
+ * This package is an SSL implementation written
+ * by Eric Young (eay@cryptsoft.com).
+ * The implementation was written so as to conform with Netscapes SSL.
+ *
+ * This library is free for commercial and non-commercial use as long as
+ * the following conditions are aheared to. The following conditions
+ * apply to all code found in this distribution, be it the RC4, RSA,
+ * lhash, DES, etc., code; not just the SSL code. The SSL documentation
+ * included with this distribution is covered by the same copyright terms
+ * except that the holder is Tim Hudson (tjh@cryptsoft.com).
+ *
+ * Copyright remains Eric Young's, and as such any Copyright notices in
+ * the code are not to be removed.
+ * If this package is used in a product, Eric Young should be given attribution
+ * as the author of the parts of the library used.
+ * This can be in the form of a textual message at program startup or
+ * in documentation (online or textual) provided with the package.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * "This product includes cryptographic software written by
+ * Eric Young (eay@cryptsoft.com)"
+ * The word 'cryptographic' can be left out if the rouines from the library
+ * being used are not cryptographic related :-).
+ * 4. If you include any Windows specific code (or a derivative thereof) from
+ * the apps directory (application code) you must include an acknowledgement:
+ * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * The licence and distribution terms for any publically available version or
+ * derivative of this code cannot be changed. i.e. this code cannot simply be
+ * copied and put under another distribution licence
+ * [including the GNU Public Licence.]
+ */
+
+------
+
+** Python 3.9.11; version 3.9.11 -- https://github.com/python/cpython/tree/v3.9.11
+Copyright Β© 2001-2020 Python Software Foundation. All rights reserved.
+
+PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
+--------------------------------------------
+
+1. This LICENSE AGREEMENT is between the Python Software Foundation
+("PSF"), and the Individual or Organization ("Licensee") accessing and
+otherwise using this software ("Python") in source or binary form and
+its associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement, PSF hereby
+grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
+analyze, test, perform and/or display publicly, prepare derivative works,
+distribute, and otherwise use Python alone or in any derivative version,
+provided, however, that PSF's License Agreement and PSF's notice of copyright,
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
+2010,
+2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software
+Foundation;
+All Rights Reserved" are retained in Python alone or in any derivative version
+prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates Python or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to Python.
+
+4. PSF is making Python available to Licensee on an "AS IS"
+basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
+DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
+FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
+INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
+FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
+A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
+OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between PSF and
+Licensee. This License Agreement does not grant permission to use PSF
+trademarks or trade name in a trademark sense to endorse or promote
+products or services of Licensee, or any third party.
+
+8. By copying, installing or otherwise using Python, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
+
+
+------
+
+** docutils; version 0.15.2 --
+https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/
+:Author: David Goodger
+:Contact: goodger@python.org
+:Date: $Date: 2015-05-08 15:56:32 +0000 (Fri, 08 May 2015) $
+:Web site: http://docutils.sourceforge.net/
+:Copyright: This document has been placed in the public domain.
+
+==================
+ Copying Docutils
+==================
+
+:Author: David Goodger
+:Contact: goodger@python.org
+:Date: $Date: 2015-05-08 15:56:32 +0000 (Fri, 08 May 2015) $
+:Web site: http://docutils.sourceforge.net/
+:Copyright: This document has been placed in the public domain.
+
+Most of the files included in this project have been placed in the
+public domain, and therefore have no license requirements and no
+restrictions on copying or usage; see the `Public Domain Dedication`_
+below. There are a few exceptions_, listed below.
+Files in the Sandbox_ are not distributed with Docutils releases and
+may have different license terms.
+
+
+Public Domain Dedication
+========================
+
+The persons who have associated their work with this project (the
+"Dedicator": David Goodger and the many contributors to the Docutils
+project) hereby dedicate the entire copyright, less the exceptions_
+listed below, in the work of authorship known as "Docutils" identified
+below (the "Work") to the public domain.
+
+The primary repository for the Work is the Internet World Wide Web
+site . The Work consists of the
+files within the "docutils" module of the Docutils project Subversion
+repository (Internet host docutils.svn.sourceforge.net, filesystem path
+/svnroot/docutils), whose Internet web interface is located at
+ . Files dedicated to the
+public domain may be identified by the inclusion, near the beginning
+of each file, of a declaration of the form::
+
+ Copyright: This document/module/DTD/stylesheet/file/etc. has been
+ placed in the public domain.
+
+Dedicator makes this dedication for the benefit of the public at large
+and to the detriment of Dedicator's heirs and successors. Dedicator
+intends this dedication to be an overt act of relinquishment in
+perpetuity of all present and future rights under copyright law,
+whether vested or contingent, in the Work. Dedicator understands that
+such relinquishment of all rights includes the relinquishment of all
+rights to enforce (by lawsuit or otherwise) those copyrights in the
+Work.
+
+Dedicator recognizes that, once placed in the public domain, the Work
+may be freely reproduced, distributed, transmitted, used, modified,
+built upon, or otherwise exploited by anyone for any purpose,
+commercial or non-commercial, and in any way, including by methods
+that have not yet been invented or conceived.
+
+(This dedication is derived from the text of the `Creative Commons
+Public Domain Dedication`. [#]_)
+
+.. [#] Creative Commons has `retired this legal tool`__ and does not
+ recommend that it be applied to works: This tool is based on United
+ States law and may not be applicable outside the US. For dedicating new
+ works to the public domain, Creative Commons recommend the replacement
+ Public Domain Dedication CC0_ (CC zero, "No Rights Reserved"). So does
+ the Free Software Foundation in its license-list_.
+
+ __ http://creativecommons.org/retiredlicenses
+ .. _CC0: http://creativecommons.org/about/cc0
+
+Exceptions
+==========
+
+The exceptions to the `Public Domain Dedication`_ above are:
+
+* docutils/writers/s5_html/themes/default/iepngfix.htc:
+
+ IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull
+ . Free usage permitted as long as
+ this notice remains intact.
+
+* docutils/utils/math/__init__.py,
+ docutils/utils/math/latex2mathml.py,
+ docutils/writers/xetex/__init__.py,
+ docutils/writers/latex2e/docutils-05-compat.sty,
+ docs/user/docutils-05-compat.sty.txt,
+ docutils/utils/error_reporting.py,
+ docutils/test/transforms/test_smartquotes.py:
+
+ Copyright Β© GΓΌnter Milde.
+ Released under the terms of the `2-Clause BSD license`_
+ (`local copy `__).
+
+* docutils/utils/smartquotes.py
+
+ Copyright Β© 2011 GΓΌnter Milde,
+ based on `SmartyPants`_ Β© 2003 John Gruber
+ (released under a 3-Clause BSD license included in the file)
+ and smartypants.py Β© 2004, 2007 Chad Miller.
+ Released under the terms of the `2-Clause BSD license`_
+ (`local copy `__).
+
+ .. _SmartyPants: http://daringfireball.net/projects/smartypants/
+
+* docutils/utils/math/math2html.py,
+ docutils/writers/html4css1/math.css
+
+ Copyright Β© Alex FernΓ‘ndez
+ These files are part of eLyXer_, released under the `GNU
+ General Public License`_ version 3 or later. The author relicensed
+ them for Docutils under the terms of the `2-Clause BSD license`_
+ (`local copy `__).
+
+ .. _eLyXer: http://www.nongnu.org/elyxer/
+
+* docutils/utils/roman.py, copyright by Mark Pilgrim, released under the
+ `Python 2.1.1 license`_ (`local copy`__).
+
+ __ licenses/python-2-1-1.txt
+
+* tools/editors/emacs/rst.el, copyright by Free Software Foundation,
+ Inc., released under the `GNU General Public License`_ version 3 or
+ later (`local copy`__).
+
+ __ licenses/gpl-3-0.txt
+
+The `2-Clause BSD license`_ and the Python licenses are OSI-approved_
+and GPL-compatible_.
+
+Plaintext versions of all the linked-to licenses are provided in the
+licenses_ directory.
+
+.. _sandbox: http://docutils.sourceforge.net/sandbox/README.html
+.. _licenses: licenses/
+.. _Python 2.1.1 license: http://www.python.org/2.1.1/license.html
+.. _GNU General Public License: http://www.gnu.org/copyleft/gpl.html
+.. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
+.. _OSI-approved: http://opensource.org/licenses/
+.. _license-list:
+.. _GPL-compatible: http://www.gnu.org/licenses/license-list.html
\ No newline at end of file
diff --git a/aws/install b/aws/install
new file mode 100644
index 0000000000000000000000000000000000000000..e9a0bf4fe9035ddc7d86041fd79f07e3e6dfef13
--- /dev/null
+++ b/aws/install
@@ -0,0 +1,155 @@
+#!/bin/sh
+# Copyright 2012-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
+# the License is located at
+#
+# http://aws.amazon.com/apache2.0/
+#
+# or in the "license" file accompanying this file. This file 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.
+
+usage() {
+ cat 1>&2 < The directory to install the AWS CLI v2. By
+ default, this directory is: /usr/local/aws-cli
+
+ -b, --bin-dir The directory to store symlinks to executables
+ for the AWS CLI v2. By default, the directory
+ used is: /usr/local/bin
+EOF
+}
+
+parse_commandline() {
+ while test $# -gt 0
+ do
+ key="$1"
+ case "$key" in
+ -i|--install-dir)
+ PARSED_INSTALL_DIR="$2"
+ shift
+ ;;
+ -b|--bin-dir)
+ PARSED_BIN_DIR="$2"
+ shift
+ ;;
+ -u|--update)
+ PARSED_UPGRADE="yes"
+ ;;
+ -h|--help)
+ usage
+ exit 0
+ ;;
+ *)
+ die "Got an unexpected argument: $1"
+ ;;
+ esac
+ shift
+ done
+}
+
+set_global_vars() {
+ ROOT_INSTALL_DIR=${PARSED_INSTALL_DIR:-/usr/local/aws-cli}
+ BIN_DIR=${PARSED_BIN_DIR:-/usr/local/bin}
+ UPGRADE=${PARSED_UPGRADE:-no}
+
+ EXE_NAME="aws"
+ COMPLETER_EXE_NAME="aws_completer"
+ INSTALLER_DIR="$( cd "$( dirname "$0" )" >/dev/null 2>&1 && pwd )"
+ INSTALLER_DIST_DIR="$INSTALLER_DIR/dist"
+ INSTALLER_EXE="$INSTALLER_DIST_DIR/$EXE_NAME"
+ AWS_EXE_VERSION=$($INSTALLER_EXE --version | cut -d ' ' -f 1 | cut -d '/' -f 2)
+
+ INSTALL_DIR="$ROOT_INSTALL_DIR/v2/$AWS_EXE_VERSION"
+ INSTALL_DIR="$INSTALL_DIR"
+ INSTALL_DIST_DIR="$INSTALL_DIR/dist"
+ INSTALL_BIN_DIR="$INSTALL_DIR/bin"
+ INSTALL_AWS_EXE="$INSTALL_BIN_DIR/$EXE_NAME"
+ INSTALL_AWS_COMPLETER_EXE="$INSTALL_BIN_DIR/$COMPLETER_EXE_NAME"
+
+ CURRENT_INSTALL_DIR="$ROOT_INSTALL_DIR/v2/current"
+ CURRENT_AWS_EXE="$CURRENT_INSTALL_DIR/bin/$EXE_NAME"
+ CURRENT_AWS_COMPLETER_EXE="$CURRENT_INSTALL_DIR/bin/$COMPLETER_EXE_NAME"
+
+ BIN_AWS_EXE="$BIN_DIR/$EXE_NAME"
+ BIN_AWS_COMPLETER_EXE="$BIN_DIR/$COMPLETER_EXE_NAME"
+}
+
+create_install_dir() {
+ mkdir -p "$INSTALL_DIR" || exit 1
+ {
+ setup_install_dist &&
+ setup_install_bin &&
+ create_current_symlink
+ } || {
+ rm -rf "$INSTALL_DIR"
+ exit 1
+ }
+}
+
+check_preexisting_install() {
+ if [ -L "$CURRENT_INSTALL_DIR" ] && [ "$UPGRADE" = "no" ]
+ then
+ die "Found preexisting AWS CLI installation: $CURRENT_INSTALL_DIR. Please rerun install script with --update flag."
+ fi
+ if [ -d "$INSTALL_DIR" ]
+ then
+ echo "Found same AWS CLI version: $INSTALL_DIR. Skipping install."
+ exit 0
+ fi
+}
+
+setup_install_dist() {
+ cp -r "$INSTALLER_DIST_DIR" "$INSTALL_DIST_DIR"
+}
+
+setup_install_bin() {
+ mkdir -p "$INSTALL_BIN_DIR"
+ ln -s "../dist/$EXE_NAME" "$INSTALL_AWS_EXE"
+ ln -s "../dist/$COMPLETER_EXE_NAME" "$INSTALL_AWS_COMPLETER_EXE"
+}
+
+create_current_symlink() {
+ ln -snf "$INSTALL_DIR" "$CURRENT_INSTALL_DIR"
+}
+
+create_bin_symlinks() {
+ mkdir -p "$BIN_DIR"
+ ln -sf "$CURRENT_AWS_EXE" "$BIN_AWS_EXE"
+ ln -sf "$CURRENT_AWS_COMPLETER_EXE" "$BIN_AWS_COMPLETER_EXE"
+}
+
+die() {
+ err_msg="$1"
+ echo "$err_msg" >&2
+ exit 1
+}
+
+main() {
+ parse_commandline "$@"
+ set_global_vars
+ check_preexisting_install
+ create_install_dir
+ create_bin_symlinks
+ echo "You can now run: $BIN_AWS_EXE --version"
+ exit 0
+}
+
+main "$@" || exit 1
diff --git a/awscliv2.zip b/awscliv2.zip
new file mode 100644
index 0000000000000000000000000000000000000000..4b478af64e83fdff6baec499510a0a3685d55bf7
--- /dev/null
+++ b/awscliv2.zip
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:41ced963f9c2193fe875d7b21c5873980cc482ae7f054e5db9a7f66b11069624
+size 66108930
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..3886c96074541c067285ac225b82b97fa9743bd1
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,41 @@
+[build-system]
+requires = ["setuptools>=61.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "videollama2"
+version = "1.0"
+description = "Release of VideoLLaMA2"
+readme = "README.md"
+requires-python = ">=3.8"
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: Apache Software License",
+]
+dependencies = [
+ "torch==2.2.0", "torchvision==0.17.0",
+ "transformers==4.40.0", "tokenizers==0.19.1",
+ "deepspeed==0.13.1", "accelerate==0.26.1",
+ "peft==0.4.0", "timm==1.0.3", "numpy==1.24.4",
+ "decord==0.6.0", "imageio==2.34.0", "imageio-ffmpeg==0.4.9",
+ "moviepy==1.0.3", "scenedetect==0.6.3",
+ "opencv-python==4.6.0.66", "pysubs2",
+ "scikit-learn==1.2.2", "huggingface_hub==0.23.4", "sentencepiece==0.1.99",
+ "shortuuid", "einops==0.6.1", "einops-exts==0.0.4",
+ "bitsandbytes==0.43.0", "pydantic>=2.0", "markdown2[all]",
+ "gradio==3.50.0", "gradio_client==0.6.1", "httpx==0.24.1",
+ "requests", "openai", "uvicorn", "fastapi", "tensorboard", "wandb", "tabulate"
+]
+
+[project.optional-dependencies]
+train = ["ninja"]
+
+[project.urls]
+"Homepage" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2"
+"Bug Tracker" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues"
+
+[tool.setuptools.packages.find]
+exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"]
+
+[tool.wheel]
+exclude = ["assets*", "benchmark*", "docs", "dist*", "playground*", "scripts*", "tests*"]
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..60f8d68e325936b646c3c1711b6880b6de47ae5a
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,40 @@
+--extra-index-url https://download.pytorch.org/whl/cu118
+# basic dependencies
+torch==2.2.0
+torchvision==0.17.0
+transformers==4.40.0
+tokenizers==0.19.1
+deepspeed==0.13.1
+accelerate==0.26.1
+peft==0.4.0
+timm==1.0.3
+numpy==1.24.4
+# data processing
+decord==0.6.0
+imageio==2.34.0
+imageio-ffmpeg==0.4.9
+moviepy==1.0.3
+scenedetect==0.6.3
+opencv-python==4.6.0.66
+pysubs2
+# misc
+scikit-learn==1.2.2
+huggingface_hub==0.23.4
+sentencepiece==0.1.99
+shortuuid
+einops==0.6.1
+einops-exts==0.0.4
+bitsandbytes==0.43.0
+pydantic>=2.0
+markdown2[all]
+gradio==3.50.0
+gradio_client==0.6.1
+httpx==0.24.1
+requests
+openai
+uvicorn
+fastapi
+tensorboard
+wandb
+tabulate
+spaces==0.29.2
\ No newline at end of file
diff --git a/scripts/custom/finetune.sh b/scripts/custom/finetune.sh
new file mode 100644
index 0000000000000000000000000000000000000000..550fdcf2029647b4a1b88ca1f5a0837659e0b7d8
--- /dev/null
+++ b/scripts/custom/finetune.sh
@@ -0,0 +1,74 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2
+RUN_NAME=downstream_sft_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --mm_projector_type stc_connector \
+ --pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2-7B-Base/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/custom/finetune_lora.sh b/scripts/custom/finetune_lora.sh
new file mode 100644
index 0000000000000000000000000000000000000000..522f2cc5858f07d64ac3ff5957f64c5ca615de1a
--- /dev/null
+++ b/scripts/custom/finetune_lora.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2
+RUN_NAME=downstream_sft_settings_lora
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --mm_projector_type stc_connector \
+ --pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2-7B-Base/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/custom/finetune_qlora.sh b/scripts/custom/finetune_qlora.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2f2e966e2c50e8ef1be5c79a68fe0c3bcb919772
--- /dev/null
+++ b/scripts/custom/finetune_qlora.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2
+RUN_NAME=downstream_sft_settings_qlora
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 --bits 4 \
+ --deepspeed scripts/zero2.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --mm_projector_type stc_connector \
+ --pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2-7B-Base/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/eval/eval_video_cap_msvc.sh b/scripts/eval/eval_video_cap_msvc.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3d8ff85d5162ad150a33c7eaa41b6bcfa37bb9d1
--- /dev/null
+++ b/scripts/eval/eval_video_cap_msvc.sh
@@ -0,0 +1,67 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/merge.json
+
+# judge if the number of json lines is 0
+if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
+ rm -f ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/*.json
+fi
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_cap_msvc.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/msvc \
+ --question-file ${EVAL_DATA_DIR}/msvc/msvc.json \
+ --output-file ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_cap_msvc_correctness.py \
+ --pred-path $output_file \
+ --output-dir ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/correctness_gpt \
+ --output-json ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/correctness_results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4 \
+
+python3 videollama2/eval/eval_video_cap_msvc_detailedness.py \
+ --pred-path $output_file \
+ --output-dir ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/detailedness_gpt \
+ --output-json ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/detailedness_results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4 \
diff --git a/scripts/eval/eval_video_mcqa_egoschema.sh b/scripts/eval/eval_video_mcqa_egoschema.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2492251837cb2b801f1a99d9467410af51a8d0cb
--- /dev/null
+++ b/scripts/eval/eval_video_mcqa_egoschema.sh
@@ -0,0 +1,41 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/merge.csv
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_egoschema.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/egoschema/good_clips_git \
+ --question-file ${EVAL_DATA_DIR}/egoschema/questions.json \
+ --answer-file ${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.csv \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ echo 'q_uid, answer' >> "$output_file"
+
+ # Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.csv >> "$output_file"
+ done
+fi
\ No newline at end of file
diff --git a/scripts/eval/eval_video_mcqa_mvbench.sh b/scripts/eval/eval_video_mcqa_mvbench.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3e18ea78430f9518a474d3f69eed9573725153ef
--- /dev/null
+++ b/scripts/eval/eval_video_mcqa_mvbench.sh
@@ -0,0 +1,46 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/merge.json
+
+# judge if the number of json lines is 0
+if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
+ rm -f ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/*.json
+fi
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_mvbench.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/mvbench/video \
+ --question-file ${EVAL_DATA_DIR}/mvbench/json \
+ --answer-file ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ # Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+python3 videollama2/eval/eval_video_mcqa_mvbench.py \
+ --pred_path ${output_file} \
diff --git a/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh b/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..abc89edc636f9da975e27179ba8fcc8a0b1893ec
--- /dev/null
+++ b/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh
@@ -0,0 +1,45 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_perception_test_mcqa.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/perception_test_mcqa/videos \
+ --question-file ${EVAL_DATA_DIR}/perception_test_mcqa/mc_question_test.json \
+ --answer-file ${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ echo "{" >> "$output_file"
+
+ # Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+
+ sed -i '$s/.$//' $output_file
+
+ echo "}" >> "$output_file"
+fi
\ No newline at end of file
diff --git a/scripts/eval/eval_video_mcqa_videomme.sh b/scripts/eval/eval_video_mcqa_videomme.sh
new file mode 100644
index 0000000000000000000000000000000000000000..aa86be7b587802a6a242178352d38ba5bc8f0e79
--- /dev/null
+++ b/scripts/eval/eval_video_mcqa_videomme.sh
@@ -0,0 +1,84 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B-16F
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/merge.json
+output_sub_file=${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/merge_sub.json
+
+# judge if the number of json lines is 0
+if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
+ rm -f ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/*.json
+fi
+
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_videomme.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videomme/videos \
+ --subtitle-folder ${EVAL_DATA_DIR}/videomme/subtitles \
+ --question-file ${EVAL_DATA_DIR}/videomme/test-00000-of-00001.parquet \
+ --answer-file ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ echo "[" >> "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+
+ sed -i '$s/.$//' $output_file
+
+ echo "]" >> "$output_file"
+
+ # Clear out the output file if it exists.
+ > "$output_sub_file"
+
+ echo "[" >> "$output_sub_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}_sub.json >> "$output_sub_file"
+ done
+
+ sed -i '$s/.$//' $output_sub_file
+
+ echo "]" >> "$output_sub_file"
+fi
+
+
+python videollama2/eval/eval_video_mcqa_videomme.py \
+ --results_file $output_file \
+ --video_duration_type "short,medium,long" \
+ --return_categories_accuracy \
+ --return_sub_categories_accuracy \
+ --return_task_types_accuracy \
+ --skip_missing \
+
+python videollama2/eval/eval_video_mcqa_videomme.py \
+ --results_file $output_sub_file \
+ --video_duration_type "short,medium,long" \
+ --return_categories_accuracy \
+ --return_sub_categories_accuracy \
+ --return_task_types_accuracy \
+ --skip_missing \
diff --git a/scripts/eval/eval_video_oqa_activitynet.sh b/scripts/eval/eval_video_oqa_activitynet.sh
new file mode 100644
index 0000000000000000000000000000000000000000..52bbfc82a46492efebd60470647b5904a473dbe2
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_activitynet.sh
@@ -0,0 +1,54 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+# CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT=work_dirs/videollama2gemma2/finetune_2b_vllama2
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_activitynet.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/all_test \
+ --question-file ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/test_q.json \
+ --answer-file ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/test_a.json \
+ --output-file ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_activitynet.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_msvd.sh b/scripts/eval/eval_video_oqa_msvd.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9d2908048e7a157cb73d7f4ee603aef5e533d8da
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_msvd.sh
@@ -0,0 +1,54 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_activitynet.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/videos \
+ --question-file ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/test_q.json \
+ --answer-file ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/test_a.json \
+ --output-file ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_activitynet.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh b/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh
new file mode 100644
index 0000000000000000000000000000000000000000..301b6e726253ae4f41748380aa1569d7422fa46b
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh
@@ -0,0 +1,58 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_general.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
+ --question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
+ --answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh b/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a88c4c89fd160862371b10bd3f9b8591fd3fea91
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh
@@ -0,0 +1,58 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/run_inference_video_qa_gpt_general.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
+ --question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
+ --answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_vcgpt_3_context.sh b/scripts/eval/eval_video_oqa_vcgpt_3_context.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f4e7d15b52877d32fbdd60214f8a61dd80fa9174
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_vcgpt_3_context.sh
@@ -0,0 +1,58 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
+
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/run_inference_video_qa_gpt_general.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
+ --question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
+ --answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}
+ mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
+ cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_vcgpt_3_context.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh b/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f653ae0ad0545c3e75432038498b7d0c4d6b8c7b
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh
@@ -0,0 +1,54 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/merge.json
+
+# if output_file not exists then inference
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_general.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
+ --question-file ${EVAL_DATA_DIR}/videochatgpt_gen/temporal_qa.json \
+ --answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh b/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh
new file mode 100644
index 0000000000000000000000000000000000000000..185521f75b0f548a1540e40b4d3c1bf607d4ede4
--- /dev/null
+++ b/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh
@@ -0,0 +1,54 @@
+set -x
+
+EVAL_DATA_DIR=eval
+OUTPUT_DIR=eval_output
+CKPT=DAMO-NLP-SG/VideoLLaMA2-7B
+CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
+
+gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
+IFS=',' read -ra GPULIST <<< "$gpu_list"
+
+# divide data via the number of GPUs per task
+GPUS_PER_TASK=1
+CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
+
+output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/merge.json
+
+# if output_file not exists then inference
+if [ ! -f "$output_file" ]; then
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ # select the GPUs for the task
+ gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
+ TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_consistency.py \
+ --model-path ${CKPT} \
+ --video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
+ --question-file ${EVAL_DATA_DIR}/videochatgpt_gen/consistency_qa.json \
+ --answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
+ --num-chunks $CHUNKS \
+ --chunk-idx $IDX &
+ done
+
+ wait
+
+ # Clear out the output file if it exists.
+ > "$output_file"
+
+ #Loop through the indices and concatenate each file.
+ for IDX in $(seq 0 $((CHUNKS-1))); do
+ cat ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
+ done
+fi
+
+
+AZURE_API_KEY=your_key
+AZURE_API_ENDPOINT=your_endpoint
+AZURE_API_DEPLOYNAME=your_deployname
+
+python3 videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py \
+ --pred-path ${output_file} \
+ --output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/gpt \
+ --output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/results.json \
+ --api-key $AZURE_API_KEY \
+ --api-endpoint $AZURE_API_ENDPOINT \
+ --api-deployname $AZURE_API_DEPLOYNAME \
+ --num-tasks 4
diff --git a/scripts/siglip/finetune_gemma2.sh b/scripts/siglip/finetune_gemma2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3d2034c785e7f54155104fc38be9019b797e7d67
--- /dev/null
+++ b/scripts/siglip/finetune_gemma2.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16667
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2gemma2_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_gemma2 \
+ --model_path google/gemma-2-2b-it \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 3 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 200 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name finetune_$RUN_NAME \
diff --git a/scripts/siglip/finetune_mistral.sh b/scripts/siglip/finetune_mistral.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9a0487cced47fcc6349d3d6e863e2bb1334e86cc
--- /dev/null
+++ b/scripts/siglip/finetune_mistral.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16667
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2mistral_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 3 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 200 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to wandb \
+ --run_name finetune_$RUN_NAME \
diff --git a/scripts/siglip/finetune_phi3.sh b/scripts/siglip/finetune_phi3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..166eacab5d88fdbc3b532d7edb5ed9f126896750
--- /dev/null
+++ b/scripts/siglip/finetune_phi3.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16667
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2phi3_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_phi3 \
+ --model_path microsoft/Phi-3-mini-4k-instruct \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 3 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 200 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name finetune_$RUN_NAME \
diff --git a/scripts/siglip/finetune_qwen2.sh b/scripts/siglip/finetune_qwen2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e232f5ed34655f00588f1aec2c54dd869f04bb39
--- /dev/null
+++ b/scripts/siglip/finetune_qwen2.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2qwen2_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_qwen2 \
+ --model_path Qwen/Qwen2-7B-Instruct \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/siglip/pretrain_gemma2.sh b/scripts/siglip/pretrain_gemma2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4afc56c4fbc82a1a30f25d22ec5d7da02afc8895
--- /dev/null
+++ b/scripts/siglip/pretrain_gemma2.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=256
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2gemma2_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_gemma2 \
+ --model_path google/gemma-2-2b-it \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --tune_mm_mlp_adapter True \
+ --data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
+ --data_folder ${DATA_DIR}/videollava_pt/ \
+ --mm_vision_select_layer -2 \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 1e-3 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --lazy_preprocess True \
+ --report_to tensorboard \
+ --run_name pretrain_$RUN_NAME \
diff --git a/scripts/siglip/pretrain_mistral.sh b/scripts/siglip/pretrain_mistral.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4914e5be8f8242ef13a8623595069d233790b445
--- /dev/null
+++ b/scripts/siglip/pretrain_mistral.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=256
+LOCAL_BATCH_SIZE=8
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2mistral_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --tune_mm_mlp_adapter True \
+ --data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
+ --data_folder ${DATA_DIR}/videollava_pt/ \
+ --mm_vision_select_layer -2 \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 1e-3 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 16 \
+ --lazy_preprocess True \
+ --report_to tensorboard \
+ --run_name pretrain_$RUN_NAME \
diff --git a/scripts/siglip/pretrain_phi3.sh b/scripts/siglip/pretrain_phi3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d475fe26fc61b2496a5dc57304e3c58db5e0d02a
--- /dev/null
+++ b/scripts/siglip/pretrain_phi3.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=256
+LOCAL_BATCH_SIZE=8
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2phi3_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_phi3 \
+ --model_path microsoft/Phi-3-mini-4k-instruct \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --tune_mm_mlp_adapter True \
+ --data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
+ --data_folder ${DATA_DIR}/videollava_pt/ \
+ --mm_vision_select_layer -2 \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 1e-3 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --lazy_preprocess True \
+ --report_to tensorboard \
+ --run_name pretrain_$RUN_NAME \
diff --git a/scripts/siglip/pretrain_qwen2.sh b/scripts/siglip/pretrain_qwen2.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d3fb400e7f3af0364d4040ee7f295bddeee53ed0
--- /dev/null
+++ b/scripts/siglip/pretrain_qwen2.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=256
+LOCAL_BATCH_SIZE=8
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+echo $GRADIENT_ACCUMULATION_STEPS
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2qwen2_siglip
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2_qwen2 \
+ --model_path Qwen/Qwen2-7B-Instruct \
+ --vision_tower google/siglip-so400m-patch14-384 \
+ --mm_projector_type stc_connector_v35 \
+ --tune_mm_mlp_adapter True \
+ --data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
+ --data_folder ${DATA_DIR}/videollava_pt/ \
+ --mm_vision_select_layer -2 \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 1e-3 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --lazy_preprocess True \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/vllava/finetune.sh b/scripts/vllava/finetune.sh
new file mode 100644
index 0000000000000000000000000000000000000000..62282868d467ddde520c54bcd01d067d26a34ef3
--- /dev/null
+++ b/scripts/vllava/finetune.sh
@@ -0,0 +1,74 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=128
+LOCAL_BATCH_SIZE=4
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --mm_projector_type stc_connector_v35 \
+ --pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
+ --data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
+ --data_folder ${DATA_DIR}/videollava_sft/ \
+ --mm_vision_select_layer -2 \
+ --image_aspect_ratio pad \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 2e-5 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/scripts/vllava/pretrain.sh b/scripts/vllava/pretrain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ec76543d9ef160243d20084da908ff4dae5b222c
--- /dev/null
+++ b/scripts/vllava/pretrain.sh
@@ -0,0 +1,74 @@
+#!/bin/bash
+
+# Environment Variables
+ARG_WORLD_SIZE=${1:-1}
+ARG_NPROC_PER_NODE=${2:-8}
+ARG_MASTER_ADDR="127.0.0.1"
+ARG_MASTER_PORT=16666
+ARG_RANK=0
+
+# Multiple conditions
+if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
+ WORLD_SIZE=$ARG_WORLD_SIZE
+ NPROC_PER_NODE=$ARG_NPROC_PER_NODE
+fi
+if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
+ MASTER_ADDR=$ARG_MASTER_ADDR
+ MASTER_PORT=$ARG_MASTER_PORT
+ RANK=$ARG_RANK
+fi
+
+echo "WORLD_SIZE: $WORLD_SIZE"
+echo "NPROC_PER_NODE: $NPROC_PER_NODE"
+
+# Training Arguments
+GLOBAL_BATCH_SIZE=256
+LOCAL_BATCH_SIZE=8
+GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
+
+# Log Arguments
+export TRANSFORMERS_OFFLINE=1
+export WANDB_PROJECT=videollama2
+RUN_NAME=vllava_settings
+DATA_DIR=datasets
+OUTP_DIR=work_dirs
+
+torchrun --nnodes $WORLD_SIZE \
+ --nproc_per_node $NPROC_PER_NODE \
+ --master_addr=$MASTER_ADDR \
+ --master_port=$MASTER_PORT \
+ --node_rank $RANK \
+ videollama2/train_flash_attn.py \
+ --deepspeed scripts/zero3.json \
+ --model_type videollama2 \
+ --model_path mistralai/Mistral-7B-Instruct-v0.2 \
+ --vision_tower openai/clip-vit-large-patch14-336 \
+ --mm_projector_type stc_connector_v35 \
+ --tune_mm_mlp_adapter True \
+ --data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
+ --data_folder ${DATA_DIR}/videollava_pt/ \
+ --mm_vision_select_layer -2 \
+ --num_frames 8 \
+ --bf16 True \
+ --tf32 True \
+ --fp16 False \
+ --output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
+ --num_train_epochs 1 \
+ --per_device_train_batch_size $LOCAL_BATCH_SIZE \
+ --per_device_eval_batch_size 4 \
+ --gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
+ --evaluation_strategy "no" \
+ --save_strategy "steps" \
+ --save_steps 500 \
+ --save_total_limit 99 \
+ --learning_rate 1e-3 \
+ --weight_decay 0. \
+ --warmup_ratio 0.03 \
+ --lr_scheduler_type "cosine" \
+ --logging_steps 1 \
+ --model_max_length 2048 \
+ --gradient_checkpointing True \
+ --dataloader_num_workers 4 \
+ --lazy_preprocess True \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/serve_videos/2024-10-01/01047cc89321a1a8f88442647d59a97e_3.jpg b/serve_videos/2024-10-01/01047cc89321a1a8f88442647d59a97e_3.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..02a739d1da43ed19ef6ea036be11e7800ceed9a4
Binary files /dev/null and b/serve_videos/2024-10-01/01047cc89321a1a8f88442647d59a97e_3.jpg differ
diff --git a/serve_videos/2024-10-01/0151039fcf5ae698df36e30ec84f3681_1.jpg b/serve_videos/2024-10-01/0151039fcf5ae698df36e30ec84f3681_1.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..3edc217b4e5d25324f4f1a81b8baa4d9b50ead8b
Binary files /dev/null and b/serve_videos/2024-10-01/0151039fcf5ae698df36e30ec84f3681_1.jpg differ
diff --git a/serve_videos/2024-10-01/27da6fcd831e07c89bccca0d446c1ebf_6.jpg b/serve_videos/2024-10-01/27da6fcd831e07c89bccca0d446c1ebf_6.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..fadf423c7dea6ec00320f1fb37010f596ffaed26
Binary files /dev/null and b/serve_videos/2024-10-01/27da6fcd831e07c89bccca0d446c1ebf_6.jpg differ
diff --git a/serve_videos/2024-10-01/36ffc3ede02479166140d3754af82726_0.jpg b/serve_videos/2024-10-01/36ffc3ede02479166140d3754af82726_0.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..534d2dec8538bd9bf43064dea1ae4d0cb4b4f6dd
Binary files /dev/null and b/serve_videos/2024-10-01/36ffc3ede02479166140d3754af82726_0.jpg differ
diff --git a/serve_videos/2024-10-01/41d66b0e6c66a2ec825c217aeccfd58d_2.jpg b/serve_videos/2024-10-01/41d66b0e6c66a2ec825c217aeccfd58d_2.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..98b68a7adb554ab2917b05ad252909e994535f57
Binary files /dev/null and b/serve_videos/2024-10-01/41d66b0e6c66a2ec825c217aeccfd58d_2.jpg differ
diff --git a/serve_videos/2024-10-01/6435a100db222d818f142b8a21fe9ea8_7.jpg b/serve_videos/2024-10-01/6435a100db222d818f142b8a21fe9ea8_7.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..71b2a9b824779d576fd73c73e2e415ada5aad919
Binary files /dev/null and b/serve_videos/2024-10-01/6435a100db222d818f142b8a21fe9ea8_7.jpg differ
diff --git a/serve_videos/2024-10-01/7896f6bd33f5afed1ff70acfd8dc657a_0.jpg b/serve_videos/2024-10-01/7896f6bd33f5afed1ff70acfd8dc657a_0.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..eb486d942fd8a2a689ae33ea42a85412983b092a
Binary files /dev/null and b/serve_videos/2024-10-01/7896f6bd33f5afed1ff70acfd8dc657a_0.jpg differ
diff --git a/serve_videos/2024-10-01/8b308fd1f62b37b8b990cc87c996b14d_6.jpg b/serve_videos/2024-10-01/8b308fd1f62b37b8b990cc87c996b14d_6.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..f4e89ac0d0eb5d2a35df50d841ed803412f0dce7
Binary files /dev/null and b/serve_videos/2024-10-01/8b308fd1f62b37b8b990cc87c996b14d_6.jpg differ
diff --git a/serve_videos/2024-10-01/a2fe273d47b18c9c50cb85a2ce553572_4.jpg b/serve_videos/2024-10-01/a2fe273d47b18c9c50cb85a2ce553572_4.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..bf43ff0065c3edf1b8bb5968a5853ae03e50e59f
Binary files /dev/null and b/serve_videos/2024-10-01/a2fe273d47b18c9c50cb85a2ce553572_4.jpg differ
diff --git a/serve_videos/2024-10-01/ab3a343f94cf27fb1cda3d09b93beea3_3.jpg b/serve_videos/2024-10-01/ab3a343f94cf27fb1cda3d09b93beea3_3.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..3953192da5ebc0b3d9b6fa6b216ec04cdc69062e
Binary files /dev/null and b/serve_videos/2024-10-01/ab3a343f94cf27fb1cda3d09b93beea3_3.jpg differ
diff --git a/serve_videos/2024-10-01/c679c3c56ae2b101c9d531ff2b8700f3_7.jpg b/serve_videos/2024-10-01/c679c3c56ae2b101c9d531ff2b8700f3_7.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..88be2966ec18a83c29e36ab6b626ddf6388ca49b
Binary files /dev/null and b/serve_videos/2024-10-01/c679c3c56ae2b101c9d531ff2b8700f3_7.jpg differ
diff --git a/serve_videos/2024-10-01/dd905105090ca15014bf2e86f9ac0653_5.jpg b/serve_videos/2024-10-01/dd905105090ca15014bf2e86f9ac0653_5.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..3c21ad9f7eaed29204ce8a21b033dd1032dc39f0
Binary files /dev/null and b/serve_videos/2024-10-01/dd905105090ca15014bf2e86f9ac0653_5.jpg differ
diff --git a/serve_videos/2024-10-01/df044961384c1dee77a57a408fece21f_5.jpg b/serve_videos/2024-10-01/df044961384c1dee77a57a408fece21f_5.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..80d0369335b902980e0ba0190c8c790a99bf8f2c
Binary files /dev/null and b/serve_videos/2024-10-01/df044961384c1dee77a57a408fece21f_5.jpg differ
diff --git a/serve_videos/2024-10-01/e05d43248ae880b266520e0905e53d27_2.jpg b/serve_videos/2024-10-01/e05d43248ae880b266520e0905e53d27_2.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4a55116a482c3b563336d86a28100c533ec760d0
Binary files /dev/null and b/serve_videos/2024-10-01/e05d43248ae880b266520e0905e53d27_2.jpg differ
diff --git a/serve_videos/2024-10-01/ee1c7e13a8109ce82bce3e9c59cd194b_4.jpg b/serve_videos/2024-10-01/ee1c7e13a8109ce82bce3e9c59cd194b_4.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..8fdeee4dfb24a761a1a678d976e126e37e0ff20d
Binary files /dev/null and b/serve_videos/2024-10-01/ee1c7e13a8109ce82bce3e9c59cd194b_4.jpg differ
diff --git a/serve_videos/2024-10-01/f4970d37a7a552d0e55e497ee1eed473_1.jpg b/serve_videos/2024-10-01/f4970d37a7a552d0e55e497ee1eed473_1.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..649f9fc51c4df70c32e70f8e0130e9389af45d3a
Binary files /dev/null and b/serve_videos/2024-10-01/f4970d37a7a552d0e55e497ee1eed473_1.jpg differ
diff --git a/start.sh b/start.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7963a202603969afb5e066bec4a854dd5d6a4ee3
--- /dev/null
+++ b/start.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+
+# Set variables
+HOSTED_ZONE_ID="Z04320311ASMBEOMPIIN6" # Replace with your Hosted Zone ID
+RECORD_NAME="verblaze.tlvtech.io" # Replace with your DNS record name
+TTL=300 # Time to live for DNS record
+TYPE="A" # Record type (A, CNAME, etc.)
+
+# Command to get the desired output (example: getting your public IP address)
+OUTPUT=$(curl -s http://checkip.amazonaws.com/)
+
+# Validate the output
+if [[ -z "$OUTPUT" ]]; then
+ echo "Error: No output from command"
+ exit 1
+fi
+
+# Create JSON payload for updating the DNS record
+cat << EOF > /tmp/route53-record-update.json
+{
+ "Comment": "Auto update DNS record via script",
+ "Changes": [
+ {
+ "Action": "UPSERT",
+ "ResourceRecordSet": {
+ "Name": "$RECORD_NAME",
+ "Type": "$TYPE",
+ "TTL": $TTL,
+ "ResourceRecords": [
+ {
+ "Value": "$OUTPUT"
+ }
+ ]
+ }
+ }
+ ]
+}
+EOF
+
+# Update the Route 53 record
+aws route53 change-resource-record-sets --hosted-zone-id $HOSTED_ZONE_ID --change-batch file:///tmp/route53-record-update.json
+
+# Check if the update was successful
+if [[ $? -eq 0 ]]; then
+ echo "DNS record updated successfully with value: $OUTPUT"
+else
+ echo "Failed to update DNS record"
+ exit 1
+fi
+
+# Clean up the temporary file
+rm /tmp/route53-record-update.json
+
diff --git a/videollama2/__init__.py b/videollama2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba4f321aa8dd1111e83c737e34708e26e71b75dd
--- /dev/null
+++ b/videollama2/__init__.py
@@ -0,0 +1,114 @@
+import os
+import copy
+import warnings
+import shutil
+from functools import partial
+
+import torch
+
+from .model import load_pretrained_model
+from .mm_utils import process_image, process_video, tokenizer_multimodal_token, get_model_name_from_path, KeywordsStoppingCriteria
+from .constants import NUM_FRAMES, DEFAULT_IMAGE_TOKEN, DEFAULT_VIDEO_TOKEN, MODAL_INDEX_MAP
+
+
+def model_init(model_path=None, **kwargs):
+ model_path = "DAMO-NLP-SG/VideoLLaMA2-7B" if model_path is None else model_path
+ model_name = get_model_name_from_path(model_path)
+ tokenizer, model, processor, context_len = load_pretrained_model(model_path, None, model_name, **kwargs)
+
+ if tokenizer.pad_token is None and tokenizer.unk_token is not None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ num_frames = model.config.num_frames if hasattr(model.config, "num_frames") else NUM_FRAMES
+
+ processor = {
+ 'image': partial(process_image, processor=processor, aspect_ratio=None),
+ 'video': partial(process_video, processor=processor, aspect_ratio=None, num_frames=num_frames),
+ }
+
+ return model, processor, tokenizer
+
+
+def mm_infer(image_or_video, instruct, model, tokenizer, modal='video', **kwargs):
+ """inference api of VideoLLaMA2 for video understanding.
+
+ Args:
+ model: VideoLLaMA2 model.
+ image_or_video (torch.Tensor): image tensor (1, C, H, W) / video tensor (T, C, H, W).
+ instruct (str): text instruction for understanding video.
+ tokenizer: tokenizer.
+ do_sample (bool): whether to sample.
+ modal (str): inference modality.
+ Returns:
+ str: response of the model.
+ """
+
+ # 1. text preprocess (tag process & generate prompt).
+ if modal == 'image':
+ modal_token = DEFAULT_IMAGE_TOKEN
+ elif modal == 'video':
+ modal_token = DEFAULT_VIDEO_TOKEN
+ elif modal == 'text':
+ modal_token = ''
+ else:
+ raise ValueError(f"Unsupported modal: {modal}")
+
+ # 1. vision preprocess (load & transform image or video).
+ if modal == 'text':
+ tensor = None
+ else:
+ tensor = image_or_video.half().cuda()
+ tensor = [(tensor, modal)]
+
+ # 2. text preprocess (tag process & generate prompt).
+ if isinstance(instruct, str):
+ message = [{'role': 'user', 'content': modal_token + '\n' + instruct}]
+ elif isinstance(instruct, list):
+ message = copy.deepcopy(instruct)
+ message[0]['content'] = modal_token + '\n' + message[0]['content']
+ else:
+ raise ValueError(f"Unsupported type of instruct: {type(instruct)}")
+
+ if model.config.model_type in ['videollama2', 'videollama2_mistral', 'videollama2_mixtral']:
+ system_message = [
+ {'role': 'system', 'content': (
+ """<>\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature."""
+ """\n"""
+ """If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n< >""")
+ }
+ ]
+ else:
+ system_message = []
+
+ message = system_message + message
+ prompt = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
+
+ input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token, return_tensors='pt').unsqueeze(0).long().cuda()
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
+
+ # 3. generate response according to visual signals and prompts.
+ keywords = [tokenizer.eos_token]
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
+
+ do_sample = kwargs.get('do_sample', False)
+ temperature = kwargs.get('temperature', 0.2 if do_sample else 0.0)
+ top_p = kwargs.get('top_p', 0.9)
+ max_new_tokens = kwargs.get('max_new_tokens', 2048)
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ attention_mask=attention_masks,
+ images=tensor,
+ do_sample=do_sample,
+ temperature=temperature,
+ max_new_tokens=max_new_tokens,
+ top_p=top_p,
+ use_cache=True,
+ stopping_criteria=[stopping_criteria],
+ pad_token_id=tokenizer.eos_token_id,
+ )
+
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
+
+ return outputs
diff --git a/videollama2/constants.py b/videollama2/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba87b61becb0819594962652fd3e193a9c8c3a3f
--- /dev/null
+++ b/videollama2/constants.py
@@ -0,0 +1,32 @@
+CONTROLLER_HEART_BEAT_EXPIRATION = 30
+WORKER_HEART_BEAT_INTERVAL = 15
+
+LOGDIR = "."
+
+# Model Constants
+IGNORE_INDEX = -100
+
+# Image arguments
+IMAGE_TOKEN_INDEX = -200
+DEFAULT_IMAGE_TOKEN = ""
+DEFAULT_IMAGE_PATCH_TOKEN = ""
+DEFAULT_IM_START_TOKEN = ""
+DEFAULT_IM_END_TOKEN = ""
+IMAGE_PLACEHOLDER = ""
+
+# Video arguments
+VIDEO_TOKEN_INDEX = -201
+DEFAULT_VIDEO_TOKEN = ""
+NUM_FRAMES = 8
+MAX_FRAMES = 32
+NUM_FRAMES_PER_SECOND = 1
+
+# Audio arguments
+AUDIO_TOKEN_INDEX = -202
+DEFAULT_AUDIO_TOKEN = ""
+
+MODAL_INDEX_MAP = {
+ "": -200,
+ "": -201,
+ "": -202,
+}
diff --git a/videollama2/conversation.py b/videollama2/conversation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a59b62cd7ba36a54382d8c6db2a701186f9834a4
--- /dev/null
+++ b/videollama2/conversation.py
@@ -0,0 +1,507 @@
+import base64
+import dataclasses
+from io import BytesIO
+from enum import auto, Enum
+from typing import List, Tuple
+
+from PIL import Image
+from .constants import LOGDIR, NUM_FRAMES
+
+
+class SeparatorStyle(Enum):
+ """Different separator style."""
+ SINGLE = auto()
+ TWO = auto()
+ PLAIN = auto()
+ LLAMA2 = auto()
+ QWEN = auto()
+
+@dataclasses.dataclass
+class Conversation:
+ """A class that keeps all conversation history."""
+ system: str
+ roles: List[str]
+ messages: List[List[str]]
+ offset: int
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
+ sep: str = "###"
+ sep2: str = None
+ version: str = "Unknown"
+
+ skip_next: bool = False
+ modality: str = "image"
+
+ def get_prompt(self):
+ messages = self.messages
+ modality_token = f"<{self.modality}>"
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
+ messages = self.messages.copy()
+ init_role, init_msg = messages[0].copy()
+ init_msg = init_msg[0].replace(modality_token, "").strip()
+ if 'mmtag' in self.version:
+ messages[0] = (init_role, init_msg)
+ messages.insert(0, (self.roles[0], " "))
+ messages.insert(1, (self.roles[1], "Received."))
+ else:
+ messages[0] = (init_role, f"{modality_token}\n" + init_msg)
+
+ if self.sep_style == SeparatorStyle.SINGLE:
+ ret = self.system + self.sep
+ for role, message in messages:
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + self.sep
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.TWO:
+ seps = [self.sep, self.sep2]
+ ret = self.system + seps[0]
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + ": " + message + seps[i % 2]
+ else:
+ ret += role + ":"
+ elif self.sep_style == SeparatorStyle.LLAMA2:
+ wrap_sys = lambda msg: f"<>\n{msg}\n< >\n\n"
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
+ ret = ""
+
+ for i, (role, message) in enumerate(messages):
+ if i == 0:
+ assert message, "first message should not be none"
+ assert role == self.roles[0], "first message should come from user"
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ if i == 0: message = wrap_sys(self.system) + message
+ if i % 2 == 0:
+ message = wrap_inst(message)
+ ret += self.sep + message
+ else:
+ ret += " " + message + " " + self.sep2
+ else:
+ ret += ""
+ ret = ret.lstrip(self.sep)
+ elif self.sep_style == SeparatorStyle.QWEN:
+ ret = ""
+ # 1. Add system prompt
+ ret += self.system + self.sep + "\n"
+ # 2. Iterate message
+ for i, (role, message) in enumerate(messages):
+ if i == 0:
+ assert message, "first message should not be none"
+ assert role == self.roles[0], "first message should come from user"
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ # 2.1 Add role and message
+ ret += role + message + self.sep + "\n"
+ else:
+ # 2.2 Add generation prompt
+ ret += role
+ elif self.sep_style == SeparatorStyle.PLAIN:
+ seps = [self.sep, self.sep2]
+ ret = self.system
+ for i, (role, message) in enumerate(messages):
+ if message:
+ if type(message) is tuple:
+ message, _, _ = message
+ ret += role + message + seps[i % 2]
+ else:
+ ret += role
+ else:
+ raise ValueError(f"Invalid style: {self.sep_style}")
+
+ return ret
+
+ def append_message(self, role, message):
+ self.messages.append([role, message])
+
+ def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=800, min_len=400):
+ if image_process_mode == "Pad":
+ def expand2square(pil_img, background_color=(122, 116, 104)):
+ width, height = pil_img.size
+ if width == height:
+ return pil_img
+ elif width > height:
+ result = Image.new(pil_img.mode, (width, width), background_color)
+ result.paste(pil_img, (0, (width - height) // 2))
+ return result
+ else:
+ result = Image.new(pil_img.mode, (height, height), background_color)
+ result.paste(pil_img, ((height - width) // 2, 0))
+ return result
+ image = expand2square(image)
+ elif image_process_mode in ["Default", "Crop"]:
+ pass
+ elif image_process_mode == "Resize":
+ image = image.resize((336, 336))
+ else:
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
+ if max(image.size) > max_len:
+ max_hw, min_hw = max(image.size), min(image.size)
+ aspect_ratio = max_hw / min_hw
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ longest_edge = int(shortest_edge * aspect_ratio)
+ W, H = image.size
+ if H > W:
+ H, W = longest_edge, shortest_edge
+ else:
+ H, W = shortest_edge, longest_edge
+ image = image.resize((W, H))
+ if return_pil:
+ return image
+ else:
+ buffered = BytesIO()
+ image.save(buffered, format=image_format)
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ return img_b64_str
+
+
+ def get_videos(self, return_pil=False):
+ video_frames = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ from decord import VideoReader, cpu
+ import numpy as np
+ # here video is the file path of input video
+ msg, video, image_process_mode = msg
+ if not return_pil:
+ # return filepath
+ video_frames.append(video)
+ else:
+ # read video using decord.VideoReader
+ decord_vr = VideoReader(uri=video, ctx=cpu(0))
+ duration = len(decord_vr)
+ frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ # convert the extracted image frames into PIL objects
+ all_images = [Image.fromarray(f) for f in decord_vr.get_batch(frame_id_list).asnumpy()]
+ video_frames.extend([self.process_image(image, image_process_mode, return_pil=return_pil) for image in all_images])
+ return video_frames
+
+
+ def get_images(self, return_pil=False):
+ images = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ msg, image, image_process_mode = msg
+ image = self.process_image(image, image_process_mode, return_pil=return_pil)
+ images.append(image)
+
+ # import base64
+ # from io import BytesIO
+ # from PIL import Image
+ # # here image is a PIL object
+ # msg, image, image_process_mode = msg
+ # if image_process_mode == "Pad":
+ # def expand2square(pil_img, background_color=(122, 116, 104)):
+ # width, height = pil_img.size
+ # if width == height:
+ # return pil_img
+ # elif width > height:
+ # result = Image.new(pil_img.mode, (width, width), background_color)
+ # result.paste(pil_img, (0, (width - height) // 2))
+ # return result
+ # else:
+ # result = Image.new(pil_img.mode, (height, height), background_color)
+ # result.paste(pil_img, ((height - width) // 2, 0))
+ # return result
+ # image = expand2square(image)
+ # elif image_process_mode in ["Default", "Crop"]:
+ # pass
+ # elif image_process_mode == "Resize":
+ # image = image.resize((336, 336))
+ # else:
+ # raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
+ # max_hw, min_hw = max(image.size), min(image.size)
+ # aspect_ratio = max_hw / min_hw
+ # max_len, min_len = 800, 400
+ # shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ # longest_edge = int(shortest_edge * aspect_ratio)
+ # W, H = image.size
+ # if longest_edge != max(image.size):
+ # if H > W:
+ # H, W = longest_edge, shortest_edge
+ # else:
+ # H, W = shortest_edge, longest_edge
+ # image = image.resize((W, H))
+ # if return_pil:
+ # images.append(image)
+ # else:
+ # buffered = BytesIO()
+ # image.save(buffered, format="PNG")
+ # img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ # images.append(img_b64_str)
+ return images
+
+ def to_gradio_chatbot(self):
+ ret = []
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
+ if i % 2 == 0:
+ if type(msg) is tuple:
+ # import base64
+ # from io import BytesIO
+ # from PIL import Image
+ # msg, image, image_process_mode = msg
+ # max_hw, min_hw = max(image.size), min(image.size)
+ # aspect_ratio = max_hw / min_hw
+ # max_len, min_len = 800, 400
+ # shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
+ # longest_edge = int(shortest_edge * aspect_ratio)
+ # W, H = image.size
+ # if H > W:
+ # H, W = longest_edge, shortest_edge
+ # else:
+ # H, W = shortest_edge, longest_edge
+ # image = image.resize((W, H))
+ # buffered = BytesIO()
+ # image.save(buffered, format="JPEG")
+ # img_b64_str = base64.b64encode(buffered.getvalue()).decode()
+ # img_str = f' '
+ # display image/video in the textbox
+ msg, image_or_video, image_process_mode = msg
+ ##print("imagebox:", image)
+ if isinstance(image_or_video, Image.Image):
+ # image is PIL object
+ img_b64_str = self.process_image(image_or_video, "Default", return_pil=False, image_format='JPEG')
+ img_str = f' '
+ msg = img_str + msg.replace('', '').strip()
+ else:
+ # video is file path
+ vid_str = f' '
+ msg = vid_str + msg.replace('', '').strip()
+ ret.append([msg, None])
+ else:
+ ret.append([msg, None])
+ else:
+ ret[-1][-1] = msg
+ return ret
+
+ def copy(self):
+ return Conversation(
+ system=self.system,
+ roles=self.roles,
+ messages=[[x, y] for x, y in self.messages],
+ offset=self.offset,
+ sep_style=self.sep_style,
+ sep=self.sep,
+ sep2=self.sep2,
+ version=self.version)
+
+ def dict(self):
+ if (self.modality == "image" and len(self.get_images()) > 0) or \
+ (self.modality == "video" and len(self.get_videos()) > 0):
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ "modality": self.modality
+ }
+ return {
+ "system": self.system,
+ "roles": self.roles,
+ "messages": self.messages,
+ "offset": self.offset,
+ "sep": self.sep,
+ "sep2": self.sep2,
+ }
+
+
+conv_vicuna_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
+ ("Assistant",
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
+ "renewable and non-renewable energy sources:\n"
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
+ "energy sources are finite and will eventually run out.\n"
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
+ "and other negative effects.\n"
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
+ "have lower operational costs than non-renewable sources.\n"
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
+ "locations than non-renewable sources.\n"
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
+ ),
+ offset=2,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_llava_plain = Conversation(
+ system="",
+ roles=("", ""),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.PLAIN,
+ sep="",
+ sep2="\n"
+)
+
+conv_llava_v0_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content .",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+ version="v0_mmtag",
+)
+
+conv_llava_v0 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("Human", "Assistant"),
+ messages=(
+ ),
+ offset=0,
+ sep_style=SeparatorStyle.SINGLE,
+ sep="###",
+)
+
+conv_vicuna_v1 = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llava_v1_mmtag = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
+ "The visual content will be provided with the following format: visual content .",
+ roles=("USER", "ASSISTANT"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+ version="v1_mmtag",
+)
+
+conv_llava_v1 = Conversation(
+ system="A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="v1",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.TWO,
+ sep=" ",
+ sep2="",
+)
+
+conv_llava_llama2 = Conversation(
+ system="You are a helpful language and vision assistant. "
+ "You are able to understand the visual content that the user provides, "
+ "and assist the user with a variety of tasks using natural language.",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2=" ",
+)
+
+conv_llama2 = Conversation(
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
+
+If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2=" ",
+)
+
+conv_mistral = Conversation(
+ system="A chat between a curious user and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
+ roles=("USER", "ASSISTANT"),
+ version="llama2",
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.LLAMA2,
+ sep="",
+ sep2="",
+)
+
+conv_qwen = Conversation(
+ system="<|im_start|>system\nYou are a helpful assistant.",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.QWEN,
+ sep="<|im_end|>",
+ version="qwen",
+)
+
+conv_qwen_plain = Conversation(
+ system="",
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
+ messages=(),
+ offset=0,
+ sep_style=SeparatorStyle.PLAIN,
+ sep="<|im_end|>",
+ sep2="<|im_end|>",
+ version="qwen_plain",
+)
+
+default_conversation = conv_mistral
+conv_templates = {
+ "default": conv_vicuna_v0,
+ # pretrain template
+ "plain": conv_llava_plain,
+ # llava v0
+ "v0": conv_vicuna_v0,
+ "v0_plain": conv_llava_plain,
+ "v0_mmtag": conv_llava_v0_mmtag,
+ "llava_v0": conv_llava_v0,
+ # llava v1
+ "v1": conv_vicuna_v1,
+ "v1_mmtag": conv_llava_v1_mmtag,
+ "llava_v1": conv_llava_v1,
+ "vicuna_v1": conv_vicuna_v1,
+ # llava v1.5
+ "llava_llama2": conv_llava_llama2,
+ # llama2
+ "llama2": conv_llama2,
+ # mistral
+ "mistral": conv_mistral,
+ # qwen
+ "qwen": conv_qwen,
+ "qwen_plain": conv_qwen_plain,
+}
+
+
+if __name__ == "__main__":
+ print(default_conversation.get_prompt())
diff --git a/videollama2/eval/eval_video_cap_msvc_correctness.py b/videollama2/eval/eval_video_cap_msvc_correctness.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cfcc23b9b54d0fd2f8e1764a0212b055e8c6085
--- /dev/null
+++ b/videollama2/eval/eval_video_cap_msvc_correctness.py
@@ -0,0 +1,259 @@
+import re
+import os
+import ast
+import time
+import json
+import argparse
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+import openai
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir):
+ """
+ Evaluates question and answer pairs using GPT-3
+ Returns a score for correctness.
+ """
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = str(qa_set['a'])
+ pred = qa_set['pred']
+ try:
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the factual accuracy of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with these correct answers and determine if they are factually consistent. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Focus on the factual consistency between the predicted answer and the correct answer. The predicted answer should not contain any misinterpretations or misinformation.\n"
+ "- The predicted answer must be factually accurate and align with the video content.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Evaluate the factual accuracy of the prediction compared to the answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answers: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a factual accuracy score where the factual accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of factual consistency. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the factual accuracy score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+ # # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+ time.sleep(1)
+
+
+def longest_repeating_substring(s):
+ n = len(s)
+ dp = [[0] * (n+1) for _ in range(n+1)]
+ res = ""
+ res_length = 0
+
+ index = 0
+ for i in range(1, n+1):
+ for j in range(i+1, n+1):
+ if (dp[i-1][j-1] > 0 and dp[i-1][j-1] < (j-i)) or s[i-1] == s[j-1]:
+ dp[i][j] = dp[i-1][j-1] + 1
+ if dp[i][j] > res_length:
+ res_length = dp[i][j]
+ index = max(i, index)
+ else:
+ dp[i][j] = 0
+
+ if res_length > 0:
+ for i in range(index-res_length+1, index+1):
+ res = res + s[i-1]
+
+ return res
+
+
+def main(args):
+ if args.num_chunks > 1:
+ pred_contents = []
+ for _idx in range(args.num_chunks):
+ file = os.path.join(args.pred_path, f"{args.num_chunks}_{_idx}.json")
+ pred_contents += [json.loads(line) for line in open(file)]
+ else:
+ pred_contents = [json.loads(line) for line in open(args.pred_path)]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample["video_name"]
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample["video_name"] = f"{video_id.split('/')[-1].split('.')[0]}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x["video_name"] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample["video_name"]
+ # print(sample)
+ question = sample["question"]
+ answer = sample["answer"]
+ pred = sample["pred"]
+ qa_set = {"q": question, "a": answer, "pred": pred}
+ prediction_set[id] = qa_set
+
+ # # Set the OpenAI API key.
+ # openai.api_key = args.api_key # Your API key here
+ # if args.api_base:
+ # openai.api_base = args.api_base # Your API base here
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i : i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir) for part in all_parts]
+ print("Generate", len(all_parts), "subprocess.")
+
+ # Use a pool of workers to process the files in parallel.
+ # with Pool() as pool:
+ # pool.starmap(annotate, task_args)
+ # import pdb;pdb.set_trace()
+ annotate(*task_args[0])
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in os.listdir(output_dir):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ try:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+ except Exception as e:
+ print(f"Error: {e}")
+ pass
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ try:
+ # key = result[0].keys()[0]
+ # import pdb; pdb.set_trace()
+ for _ in result[0].keys():
+ score_match = result[0][_]
+ score = int(score_match)
+ score_sum += score
+ break
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+ import pdb; pdb.set_trace()
+ average_score = score_sum / count
+ combined_contents["average_score"] = average_score
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file, indent=4)
+ print("Average score for correctness:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--num_chunks", default=1, type=int, help="Result splits")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_cap_msvc_detailedness.py b/videollama2/eval/eval_video_cap_msvc_detailedness.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae772ab8418804a587054a4e4d7b139a9d8e67d
--- /dev/null
+++ b/videollama2/eval/eval_video_cap_msvc_detailedness.py
@@ -0,0 +1,257 @@
+import re
+import os
+import ast
+import time
+import json
+import argparse
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+import openai
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir):
+ """
+ Evaluates question and answer pairs using GPT-3
+ Returns a score for correctness.
+ """
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = str(qa_set['a'])
+ pred = qa_set['pred']
+ try:
+ message = [
+ {
+ "role": "system",
+ "content": "You are an intelligent chatbot designed for evaluating the detail orientation of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with these correct answers and determine its level of detail, considering both completeness and specificity. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Check if the predicted answer covers all major points from the video. The response should not leave out any key aspects.\n"
+ "- Evaluate whether the predicted answer includes specific details rather than just generic points. It should provide comprehensive information that is tied to specific elements of the video.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Provide a single evaluation score that reflects the level of detail orientation of the prediction, considering both completeness and specificity.",
+ },
+ {
+ "role": "user",
+ "content": "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answers: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a detail orientation score where the detail orientation score is an integer value between 0 and 5, with 5 indicating the highest level of detail orientation. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the detail orientation score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}.",
+ },
+ ]
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+ # # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+ time.sleep(1)
+
+
+def longest_repeating_substring(s):
+ n = len(s)
+ dp = [[0] * (n+1) for _ in range(n+1)]
+ res = ""
+ res_length = 0
+
+ index = 0
+ for i in range(1, n+1):
+ for j in range(i+1, n+1):
+ if (dp[i-1][j-1] > 0 and dp[i-1][j-1] < (j-i)) or s[i-1] == s[j-1]:
+ dp[i][j] = dp[i-1][j-1] + 1
+ if dp[i][j] > res_length:
+ res_length = dp[i][j]
+ index = max(i, index)
+ else:
+ dp[i][j] = 0
+
+ if res_length > 0:
+ for i in range(index-res_length+1, index+1):
+ res = res + s[i-1]
+
+ return res
+
+
+def main(args):
+ if args.num_chunks > 1:
+ pred_contents = []
+ for _idx in range(args.num_chunks):
+ file = os.path.join(args.pred_path, f"{args.num_chunks}_{_idx}.json")
+ pred_contents += [json.loads(line) for line in open(file)]
+ else:
+ pred_contents = [json.loads(line) for line in open(args.pred_path)]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample["video_name"]
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample["video_name"] = f"{video_id.split('/')[-1].split('.')[0]}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x["video_name"] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample["video_name"]
+ # print(sample)
+ question = sample["question"]
+ answer = sample["answer"]
+ pred = sample["pred"]
+ qa_set = {"q": question, "a": answer, "pred": pred}
+ prediction_set[id] = qa_set
+
+ # # Set the OpenAI API key.
+ # openai.api_key = args.api_key # Your API key here
+ # if args.api_base:
+ # openai.api_base = args.api_base # Your API base here
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i : i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir) for part in all_parts]
+ print("Generate", len(all_parts), "subprocess.")
+
+ # Use a pool of workers to process the files in parallel.
+ # with Pool() as pool:
+ # pool.starmap(annotate, task_args)
+ # import pdb;pdb.set_trace()
+ annotate(*task_args[0])
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in os.listdir(output_dir):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ try:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+ except Exception as e:
+ print(f"Error: {e}")
+ pass
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ try:
+ # key = result[0].keys()[0]
+ # import pdb; pdb.set_trace()
+ for _ in result[0].keys():
+ score_match = result[0][_]
+ score = int(score_match)
+ score_sum += score
+ break
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+ import pdb; pdb.set_trace()
+ average_score = score_sum / count
+ combined_contents["average_score"] = average_score
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file, indent=4)
+ print("Average score for detailedness:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--num_chunks", default=1, type=int, help="Result splits")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_mcqa_mvbench.py b/videollama2/eval/eval_video_mcqa_mvbench.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae1420caa45f0bb7e35e4d917d68ab93498c574d
--- /dev/null
+++ b/videollama2/eval/eval_video_mcqa_mvbench.py
@@ -0,0 +1,64 @@
+import json
+import argparse
+from tabulate import tabulate
+
+
+tasks = {
+ "Action Sequence": ("action_sequence.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Action Prediction": ("action_prediction.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Action Antonym": ("action_antonym.json", "ssv2_video/", "video", False),
+ "Fine-grained Action": ("fine_grained_action.json", "pMoments_in_Time_Raw/videos/", "video", False),
+ "Unexpected Action": ("unexpected_action.json", "FunQA_test/test/", "video", False),
+ "Object Existence": ("object_existence.json", "clevrer/video_validation/", "video", False),
+ "Object Interaction": ("object_interaction.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Object Shuffle": ("object_shuffle.json", "perception/videos/", "video", False),
+ "Moving Direction": ("moving_direction.json", "clevrer/video_validation/", "video", False),
+ "Action Localization": ("action_localization.json", "sta/sta_video/", "video", True), # has start & end
+ "Scene Transition": ("scene_transition.json", "scene_qa/video/", "video", False),
+ "Action Count": ("action_count.json", "perception/videos/", "video", False),
+ "Moving Count": ("moving_count.json", "clevrer/video_validation/", "video", False),
+ "Moving Attribute": ("moving_attribute.json", "clevrer/video_validation/", "video", False),
+ "State Change": ("state_change.json", "perception/videos/", "video", False),
+ "Fine-grained Pose": ("fine_grained_pose.json", "nturgbd/", "video", False),
+ "Character Order": ("character_order.json", "perception/videos/", "video", False),
+ "Egocentric Navigation": ("egocentric_navigation.json", "vlnqa/", "video", False),
+ "Episodic Reasoning": ("episodic_reasoning.json", "tvqa/frames_fps3_hq/", "frame", True), # has start & end, read frame
+ "Counterfactual Inference": ("counterfactual_inference.json", "clevrer/video_validation/", "video", False),
+}
+
+
+def main():
+ args = parse_args()
+ res = [eval(x.strip()) for x in open(args.pred_path, 'r').readlines()]
+ task_types = tasks.keys()
+ task_acc = {x: [] for x in task_types}
+ acc = []
+ for i, x in enumerate(res):
+ value = 1
+ if x['pred'] != x['gt']:
+ value = 0
+ acc.append(value)
+ task_acc[x['task_type']].append(value)
+ acc = sum(acc) * 100 / len(acc)
+ task_acc = {x: sum(task_acc[x]) * 100 / len(task_acc[x]) for x in task_acc}
+ print(f"{args.pred_path}:", acc)
+ task_names = list(tasks.keys())
+
+ table_data = []
+ for i in range(len(task_names) // 4):
+ row_task_names = task_names[i * 4: (i + 1) * 4]
+ row_task_acc = [task_acc[x] for x in row_task_names]
+ table_data.append(row_task_names)
+ table_data.append(row_task_acc)
+ print(tabulate(table_data, floatfmt=".1f"), '\n')
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description="Evaluate video captioning.")
+ parser.add_argument("--pred_path", default=r'', help="The path to file containing prediction.")
+ args = parser.parse_args()
+ return args
+
+
+if __name__ == '__main__':
+ main()
diff --git a/videollama2/eval/eval_video_mcqa_videomme.py b/videollama2/eval/eval_video_mcqa_videomme.py
new file mode 100644
index 0000000000000000000000000000000000000000..afca31c461132fbfce7a6d2bc7803f18db7c6f01
--- /dev/null
+++ b/videollama2/eval/eval_video_mcqa_videomme.py
@@ -0,0 +1,277 @@
+import os
+import re
+import json
+import argparse
+from typing import List, Dict, Optional, Union
+
+CATEGORIES = [
+ "Knowledge",
+ "Film & Television",
+ "Sports Competition",
+ "Artistic Performance",
+ "Life Record",
+ "Multilingual"
+]
+
+SUB_CATEGORIES = [
+ "Humanity & History",
+ "Literature & Art",
+ "Biology & Medicine",
+ "Finance & Commerce",
+ "Astronomy",
+ "Geography",
+ "Law",
+ "Life Tip",
+ "Technology",
+ "Animation",
+ "Movie & TV Show",
+ "Documentary",
+ "News Report",
+ "Esports",
+ "Basketball",
+ "Football",
+ "Athletics",
+ "Other Sports",
+ "Stage Play",
+ "Magic Show",
+ "Variety Show",
+ "Acrobatics",
+ "Handicraft",
+ "Food",
+ "Fashion",
+ "Daily Life",
+ "Travel",
+ "Pet & Animal",
+ "Exercise",
+ "Multilingual"
+]
+
+TASK_CATEGORIES = [
+ "Temporal Perception",
+ "Spatial Perception",
+ "Attribute Perception",
+ "Action Recognition",
+ "Object Recognition",
+ "OCR Problems",
+ "Counting Problem",
+ "Temporal Reasoning",
+ "Spatial Reasoning",
+ "Action Reasoning",
+ "Object Reasoning",
+ "Information Synopsis",
+]
+
+
+def extract_characters_regex(s):
+ s = s.strip()
+ answer_prefixes = [
+ "The best answer is",
+ "The correct answer is",
+ "The answer is",
+ "The answer",
+ "The best option is"
+ "The correct option is",
+ "Best answer:"
+ "Best option:",
+ ]
+ for answer_prefix in answer_prefixes:
+ s = s.replace(answer_prefix, "")
+
+ if len(s.split()) > 10 and not re.search("[ABCD]", s):
+ return ""
+ matches = re.search(r'[ABCD]', s)
+ if matches is None:
+ return ""
+ return matches[0]
+
+
+def eval_your_results(
+ your_results_path: str,
+ video_types: Optional[Union[List[str], str]] = None,
+ skip_missing: Optional[bool] = True,
+ return_categories_accuracy: Optional[bool] = True,
+ return_sub_categories_accuracy: Optional[bool] = False,
+ return_task_types_accuracy: Optional[bool] = False,
+ gt_answer_key: Optional[str] = "answer",
+ your_answer_key: Optional[str] = "response"
+
+ ):
+ """
+ Evaluate your results against the ground truth
+
+ Args:
+ - your_results_path (str): Path to your results file
+ - video_types (Optional[List[str], str]): List of video types to evaluate.
+ - skip_missing (Optional[bool]): If True, missing files will be skipped. If False, an error will be raised if there are missing files.
+ - return_categories_accuracy (Optional[bool]): If True, the accuracy for each video category will be returned.
+ - return_sub_categories_accuracy (Optional[bool]): If True, the accuracy for each video sub category will be returned.
+ - return_task_types_accuracy (Optional[bool]): If True, the accuracy for each task category will be returned.
+ - gt_answer_key (Optional[str]): Key to access the ground truth answer in the results file.
+ - your_answer_key (Optional[str]): Key to access your answer in the results file.
+ """
+
+ # Load your results
+ with open(your_results_path, 'r') as f:
+ your_results = json.load(f)
+
+ if isinstance(video_types, str):
+ video_types = video_types.split(",")
+
+ q_type_dict = {}
+ v_type_dict = {}
+ v_sub_type_dict = {}
+
+
+ for video_type in video_types:
+
+ # Filter your results based on video types
+ your_results_video_type = [item for item in your_results if item["duration"] == video_type]
+
+ # Task Categories
+ q_type_dict[video_type] = {}
+ for q_type in TASK_CATEGORIES:
+ q_type_dict[video_type][q_type] = {"correct": 0, "answered": 0}
+
+ # Video categories
+ v_type_dict[video_type] = {}
+ for v_type in CATEGORIES:
+ v_type_dict[video_type][v_type] = {"correct": 0, "answered": 0}
+
+ v_sub_type_dict[video_type] = {}
+ for v_sub_type in SUB_CATEGORIES:
+ v_sub_type_dict[video_type][v_sub_type] = {"correct": 0, "answered": 0}
+
+ if not skip_missing:
+ # Check if the number of files in your results and ground truth are the same
+ assert len(your_results_video_type) == 300, f"Number of files in {video_type} is not 300. Check if there are missing files."
+
+ for item in your_results_video_type:
+
+ if skip_missing and item["missing"]:
+ continue
+
+ # Get the video category, sub category and question category
+ video_category = item["domain"]
+ video_sub_category = item["sub_category"]
+
+ questions = item["questions"]
+
+ for question in questions:
+ q_type = question["task_type"]
+
+ # Get the ground truth and your response
+ gt_answer = question[gt_answer_key]
+ response = question[your_answer_key]
+
+ # Extract the answer from the response
+ extration = extract_characters_regex(response)
+
+ if extration != "":
+ q_type_dict[video_type][q_type]["answered"] += 1
+ q_type_dict[video_type][q_type]["correct"] += extration == gt_answer
+
+ v_type_dict[video_type][video_category]["answered"] += 1
+ v_type_dict[video_type][video_category]["correct"] += extration == gt_answer
+
+ v_sub_type_dict[video_type][video_sub_category]["answered"] += 1
+ v_sub_type_dict[video_type][video_sub_category]["correct"] += extration == gt_answer
+
+
+ # Print the results for each video type
+ for video_type in video_types:
+
+ print("=====================================")
+ print(f"Evaluation on video Type: {video_type}")
+ print("=====================================")
+ if return_categories_accuracy:
+ print("-------------------------------------")
+ print("Video Domains")
+ print("-------------------------------------")
+ for v_type in v_type_dict[video_type]:
+ print(f"{v_type}: {100 * v_type_dict[video_type][v_type]['correct'] / v_type_dict[video_type][v_type]['answered'] if v_type_dict[video_type][v_type]['answered'] > 0 else 0 : .1f}%")
+ if return_sub_categories_accuracy:
+ print("-------------------------------------")
+ print("Video Sub Categories")
+ print("-------------------------------------")
+ for v_sub_type in v_sub_type_dict[video_type]:
+ print(f"{v_sub_type}: {100 * v_sub_type_dict[video_type][v_sub_type]['correct'] / v_sub_type_dict[video_type][v_sub_type]['answered'] if v_sub_type_dict[video_type][v_sub_type]['answered'] > 0 else 0 : .1f}%")
+ if return_task_types_accuracy:
+ print("-------------------------------------")
+ print("Task Categories")
+ print("-------------------------------------")
+ for q_type in q_type_dict[video_type]:
+ print(f"{q_type}: {100 * q_type_dict[video_type][q_type]['correct'] / q_type_dict[video_type][q_type]['answered'] if q_type_dict[video_type][q_type]['answered'] > 0 else 0 : .1f}%")
+
+ print("-------------------------------------")
+ print("Overall Performance")
+ print("-------------------------------------")
+ total_correct = sum([q_type_dict[video_type][q_type]["correct"] for q_type in TASK_CATEGORIES])
+ total_answered = sum([q_type_dict[video_type][q_type]["answered"] for q_type in TASK_CATEGORIES])
+ print(f"Overall: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
+
+ print("\n")
+
+ # Print the results for the entire dataset
+ print("=====================================")
+ print("Evaluation on the entire dataset")
+ print("=====================================")
+
+ if return_categories_accuracy:
+ print("-------------------------------------")
+ print("Video Categories")
+ print("-------------------------------------")
+ for v_type in CATEGORIES:
+ total_correct = sum([v_type_dict[video_type][v_type]["correct"] for video_type in video_types])
+ total_answered = sum([v_type_dict[video_type][v_type]["answered"] for video_type in video_types])
+ print(f"{v_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
+
+
+ if return_sub_categories_accuracy:
+ print("-------------------------------------")
+ print("Video Sub Categories")
+ print("-------------------------------------")
+
+ for v_sub_type in SUB_CATEGORIES:
+ total_correct = sum([v_sub_type_dict[video_type][v_sub_type]["correct"] for video_type in video_types])
+ total_answered = sum([v_sub_type_dict[video_type][v_sub_type]["answered"] for video_type in video_types])
+ print(f"{v_sub_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
+
+
+ if return_task_types_accuracy:
+ print("-------------------------------------")
+ print("Task Categories")
+ print("-------------------------------------")
+ for q_type in TASK_CATEGORIES:
+
+ total_correct = sum([q_type_dict[video_type][q_type]["correct"] for video_type in video_types])
+ total_answered = sum([q_type_dict[video_type][q_type]["answered"] for video_type in video_types])
+ print(f"{q_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
+
+ print("-------------------------------------")
+ print("Overall Performance")
+ print("-------------------------------------")
+ total_correct = sum([sum([q_type_dict[video_type][q_type]["correct"] for q_type in TASK_CATEGORIES]) for video_type in video_types])
+ total_answered = sum([sum([q_type_dict[video_type][q_type]["answered"] for q_type in TASK_CATEGORIES]) for video_type in video_types])
+ print(f"Overall: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
+
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--results_file", type=str, required=True)
+ parser.add_argument("--video_duration_type", type=str, required=True)
+ parser.add_argument("--return_categories_accuracy", action="store_true")
+ parser.add_argument("--return_sub_categories_accuracy", action="store_true")
+ parser.add_argument("--return_task_types_accuracy", action="store_true")
+ parser.add_argument("--skip_missing", action="store_true")
+
+ args = parser.parse_args()
+
+ eval_your_results(
+ args.results_file,
+ video_types=args.video_duration_type,
+ skip_missing=args.skip_missing,
+ return_categories_accuracy=args.return_categories_accuracy,
+ return_sub_categories_accuracy=args.return_sub_categories_accuracy,
+ return_task_types_accuracy=args.return_task_types_accuracy,
+ )
diff --git a/videollama2/eval/eval_video_oqa_activitynet.py b/videollama2/eval/eval_video_oqa_activitynet.py
new file mode 100644
index 0000000000000000000000000000000000000000..f261a02e5afa672a0d45048dcea5d2c11dfdf566
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_activitynet.py
@@ -0,0 +1,210 @@
+import os
+import ast
+import json
+import time
+import argparse
+import traceback
+from tqdm import tqdm
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def prompt_gpt(question, answer, pred, key, qa_set, output_dir):
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
+ "Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Focus on the meaningful match between the predicted answer and the correct answer.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Evaluate the correctness of the prediction compared to the answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. "
+ "Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {'pred': 'yes', 'score': 4.8}."
+ }
+ ]
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+ # # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+
+def annotate(task_arg):
+ """
+ Evaluates question and answer pairs using GPT-3
+ Returns a score for correctness.
+ """
+ prediction_set, caption_files, output_dir, args = task_arg
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = qa_set['a']
+ pred = qa_set['p']
+ try:
+ prompt_gpt(question, answer, pred, key, qa_set, output_dir)
+ except Exception as e:
+ prompt_gpt(question, answer, pred[:50], key, qa_set, output_dir)
+ traceback.print_exc()
+
+ time.sleep(1)
+
+
+def main(args):
+
+ file = open(args.pred_path)
+ new_pred_contents = [eval(i.strip()) for i in file.readlines()]
+
+ # Generating list of id's and corresponding files
+ id_list = [x['id'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['id']
+ question = sample['question']
+ answer = sample['answer']
+ pred = sample['pred']
+ qa_set = {"q": question, "a": answer, "p": pred}
+ prediction_set[id] = qa_set
+
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with ThreadPoolExecutor(max_workers=args.num_tasks) as executor:
+ list(tqdm(executor.map(annotate, task_args), total=len(task_args)))
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # multiprocessing to combine json files
+ def combine_json(file_name):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ return (file_name[:-5], content)
+
+ files = os.listdir(output_dir)
+ with ThreadPoolExecutor(max_workers=64) as executor:
+ combined_contents = list(tqdm(executor.map(combine_json, files), total=len(files)))
+
+ # Calculate average score and accuracy
+ score_sum = 0
+ count = 0
+ yes_count = 0
+ no_count = 0
+ for key, result in tqdm(combined_contents):
+ try:
+ # Computing score
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+
+ # Computing accuracy
+ pred = result[0]['pred']
+ if "yes" in pred.lower():
+ yes_count += 1
+ elif "no" in pred.lower():
+ no_count += 1
+ except:
+ print(result)
+
+ average_score = score_sum / count
+ accuracy = yes_count / (yes_count + no_count)
+ print("Yes count:", yes_count)
+ print("No count:", no_count)
+ print("Accuracy:", accuracy)
+ print("Average score:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py b/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fae15c22e2b357b30850b53cd3ba4210260084a
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py
@@ -0,0 +1,210 @@
+import os
+import argparse
+import json
+import ast
+import traceback
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir, args):
+ """
+ Evaluates question and answer pairs using GPT-3
+ Returns a score for correctness.
+ """
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = qa_set['a']
+ pred = qa_set['p']
+ try:
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the factual accuracy of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with the correct answer and determine if they are factually consistent. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Focus on the factual consistency between the predicted answer and the correct answer. The predicted answer should not contain any misinterpretations or misinformation.\n"
+ "- The predicted answer must be factually accurate and align with the video content.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Evaluate the factual accuracy of the prediction compared to the answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a factual accuracy score where the factual accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of factual consistency. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the factual accuracy score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+
+ # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+
+def main(args):
+ pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample['video_name']
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x['video_name'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['video_name']
+ question = sample['Q']
+ answer = sample['A']
+ pred = sample['P']
+ qa_set = {"q": question, "a": answer, "p": pred}
+ prediction_set[id] = qa_set
+
+ # Set the OpenAI API key.
+ # openai.api_key = args.api_key
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with Pool() as pool:
+ pool.starmap(annotate, task_args)
+
+ except Exception as e:
+ traceback.print_exc()
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in tqdm(os.listdir(output_dir)):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+
+ # Write combined content to a json file
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file)
+ print("All evaluation completed!")
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+ average_score = score_sum / count
+
+ print("Average score for correctness:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py b/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py
new file mode 100644
index 0000000000000000000000000000000000000000..5da472c3afd9a75a177650806b8a1775441fd23a
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py
@@ -0,0 +1,210 @@
+import os
+import argparse
+import json
+import ast
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir, args):
+ """
+ Evaluates question and answer pairs using GPT-3 and
+ returns a score for detailed orientation.
+ """
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = qa_set['a']
+ pred = qa_set['p']
+ try:
+ # Compute the detailed-orientation score
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the detail orientation of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with the correct answer and determine its level of detail, considering both completeness and specificity. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Check if the predicted answer covers all major points from the video. The response should not leave out any key aspects.\n"
+ "- Evaluate whether the predicted answer includes specific details rather than just generic points. It should provide comprehensive information that is tied to specific elements of the video.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Provide a single evaluation score that reflects the level of detail orientation of the prediction, considering both completeness and specificity."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a detail orientation score where the detail orientation score is an integer value between 0 and 5, with 5 indicating the highest level of detail orientation. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the detail orientation score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+
+ # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+
+def main(args):
+ pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample['video_name']
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x['video_name'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['video_name']
+ question = sample['Q']
+ answer = sample['A']
+ pred = sample['P']
+ qa_set = {"q": question, "a": answer, "p": pred}
+ prediction_set[id] = qa_set
+
+ # Set the OpenAI API key.
+ # openai.api_key = args.api_key
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with Pool() as pool:
+ pool.starmap(annotate, task_args)
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in tqdm(os.listdir(output_dir)):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+
+ # Write combined content to a json file
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file)
+ print("All evaluation completed!")
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+ average_score = score_sum / count
+
+ print("Average score for detailed orientation:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_oqa_vcgpt_3_context.py b/videollama2/eval/eval_video_oqa_vcgpt_3_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..2508b19203e3c2fd73c790cd22779354f9b4d73a
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_vcgpt_3_context.py
@@ -0,0 +1,212 @@
+import os
+import argparse
+import json
+import ast
+import traceback
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir, args):
+ """
+ Evaluates question and answer pairs using GPT-3 and
+ returns a score for contextual understanding.
+ """
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = qa_set['a']
+ pred = qa_set['p']
+ try:
+ # Compute the contextual understanding score
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the contextual understanding of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with the correct answer and determine if the generated response aligns with the overall context of the video content. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Evaluate whether the predicted answer aligns with the overall context of the video content. It should not provide information that is out of context or misaligned.\n"
+ "- The predicted answer must capture the main themes and sentiments of the video.\n"
+ "- Consider synonyms or paraphrases as valid matches.\n"
+ "- Provide your evaluation of the contextual understanding of the prediction compared to the answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a contextual understanding score where the contextual understanding score is an integer value between 0 and 5, with 5 indicating the highest level of contextual understanding. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is contextual understanding score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+
+ # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+
+def main(args):
+ pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample['video_name']
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x['video_name'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['video_name']
+ question = sample['Q']
+ answer = sample['A']
+ pred = sample['P']
+ qa_set = {"q": question, "a": answer, "p": pred}
+ prediction_set[id] = qa_set
+
+ # Set the OpenAI API key.
+ # openai.api_key = args.api_key
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with Pool() as pool:
+ pool.starmap(annotate, task_args)
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in tqdm(os.listdir(output_dir)):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+
+ # Write combined content to a json file
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file)
+ print("All evaluation completed!")
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+ average_score = score_sum / count
+
+ print("Average score for contextual understanding:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py b/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py
new file mode 100644
index 0000000000000000000000000000000000000000..de3fd4c790f06113f151ed5899b59e3d5c6cfa55
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py
@@ -0,0 +1,206 @@
+import os
+import argparse
+import json
+import ast
+import traceback
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir, args):
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question = qa_set['q']
+ answer = qa_set['a']
+ pred = qa_set['p']
+ try:
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the temporal understanding of generative outputs for video-based question-answer pairs. "
+ "Your task is to compare the predicted answer with the correct answer and determine if they correctly reflect the temporal sequence of events in the video content. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Focus on the temporal consistency between the predicted answer and the correct answer. The predicted answer should correctly reflect the sequence of events or details as they are presented in the video content.\n"
+ "- Consider synonyms or paraphrases as valid matches, but only if the temporal order is maintained.\n"
+ "- Evaluate the temporal accuracy of the prediction compared to the answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question: {question}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer: {pred}\n\n"
+ "Provide your evaluation only as a temporal accuracy score where the temporal accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of temporal consistency. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the temporal accuracy score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+
+ # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+
+def main(args):
+ pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample['video_name']
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x['video_name'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['video_name']
+ question = sample['Q']
+ answer = sample['A']
+ pred = sample['P']
+ qa_set = {"q": question, "a": answer, "p": pred}
+ prediction_set[id] = qa_set
+
+ # Set the OpenAI API key.
+ # openai.api_key = args.api_key
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with Pool() as pool:
+ pool.starmap(annotate, task_args)
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in os.listdir(output_dir):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+
+ # Write combined content to a json file
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file)
+ print("All evaluation completed!")
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+ average_score = score_sum / count
+
+ print("Average score temporal understanding:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py b/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..13d39cac298d5fbc31190959585b7e36f4ae0be4
--- /dev/null
+++ b/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py
@@ -0,0 +1,218 @@
+import os
+import argparse
+import json
+import ast
+import traceback
+from tqdm import tqdm
+from multiprocessing.pool import Pool
+
+from openai import AzureOpenAI
+
+
+def init():
+ client = AzureOpenAI(
+ azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
+ api_key=os.getenv("AZURE_OPENAI_KEY"),
+ api_version="2024-02-15-preview"
+ )
+
+ return client
+
+
+def interaction(client, message_text):
+ completion = client.chat.completions.create(
+ model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
+ messages = message_text,
+ temperature=0.7,
+ max_tokens=800,
+ top_p=0.95,
+ frequency_penalty=0,
+ presence_penalty=0,
+ stop=None
+ )
+
+ return completion
+
+
+def annotate(prediction_set, caption_files, output_dir, args):
+ """
+ Evaluates question and answer pairs using GPT-3 and
+ returns a score for consistency.
+ """
+
+ for file in tqdm(caption_files):
+ key = file[:-5] # Strip file extension
+ qa_set = prediction_set[key]
+ question1 = qa_set['q1']
+ question2 = qa_set['q2']
+ answer = qa_set['a']
+ pred1 = qa_set['p1']
+ pred2 = qa_set['p2']
+ try:
+ message = [
+ {
+ "role": "system",
+ "content":
+ "You are an intelligent chatbot designed for evaluating the consistency of generative outputs for similar video-based question-answer pairs. "
+ "You will be given two very similar questions, a common answer common to both the questions and predicted answers for the two questions ."
+ "Your task is to compare the predicted answers for two very similar question, with a common correct answer and determine if they are consistent. Here's how you can accomplish the task:"
+ "------"
+ "##INSTRUCTIONS: "
+ "- Focus on the consistency between the two predicted answers and the correct answer. Both predicted answers should correspond to the correct answer and to each other, and should not contain any contradictions or significant differences in the conveyed information.\n"
+ "- Both predicted answers must be consistent with each other and the correct answer, in terms of the information they provide about the video content.\n"
+ "- Consider synonyms or paraphrases as valid matches, but only if they maintain the consistency in the conveyed information.\n"
+ "- Evaluate the consistency of the two predicted answers compared to the correct answer."
+ },
+ {
+ "role": "user",
+ "content":
+ "Please evaluate the following video-based question-answer pair:\n\n"
+ f"Question 1: {question1}\n"
+ f"Question 2: {question2}\n"
+ f"Correct Answer: {answer}\n"
+ f"Predicted Answer to Question 1: {pred1}\n"
+ f"Predicted Answer to Question 2: {pred2}\n\n"
+ "Provide your evaluation only as a consistency score where the consistency score is an integer value between 0 and 5, with 5 indicating the highest level of consistency. "
+ "Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the consistency score in INTEGER, not STRING."
+ "DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
+ "For example, your response should look like this: {''score': 4.8}."
+ }
+ ]
+
+ completion = interaction(client, message)
+ # Convert response to a Python dictionary.
+ response_message = completion.choices[0].message.content
+ response_dict = ast.literal_eval(response_message)
+ result_qa_pair = [response_dict, qa_set]
+
+ # Save the question-answer pairs to a json file.
+ with open(f"{output_dir}/{key}.json", "w") as f:
+ json.dump(result_qa_pair, f)
+
+ except Exception as e:
+ print(f"Error processing file '{key}': {e}")
+
+
+def main(args):
+ pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
+
+ # Dictionary to store the count of occurrences for each video_id
+ video_id_counts = {}
+ new_pred_contents = []
+
+ # Iterate through each sample in pred_contents
+ for sample in pred_contents:
+ video_id = sample['video_name']
+ if video_id in video_id_counts:
+ video_id_counts[video_id] += 1
+ else:
+ video_id_counts[video_id] = 0
+
+ # Create a new sample with the modified key
+ new_sample = sample
+ new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
+ new_pred_contents.append(new_sample)
+
+ # Generating list of id's and corresponding files
+ id_list = [x['video_name'] for x in new_pred_contents]
+ caption_files = [f"{id}.json" for id in id_list]
+
+ output_dir = args.output_dir
+ # Generate output directory if not exists.
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+
+ # Preparing dictionary of question-answer sets
+ prediction_set = {}
+ for sample in new_pred_contents:
+ id = sample['video_name']
+ question1 = sample['Q1']
+ question2 = sample['Q2']
+ answer = sample['A']
+ pred1 = sample['P1']
+ pred2 = sample['P2']
+ qa_set = {"q1": question1, "q2": question2, "a": answer, "p1": pred1, "p2": pred2}
+ prediction_set[id] = qa_set
+
+ # Set the OpenAI API key.
+ # openai.api_key = args.api_key
+ num_tasks = args.num_tasks
+
+ # While loop to ensure that all captions are processed.
+ while True:
+ try:
+ # Files that have not been processed yet.
+ completed_files = os.listdir(output_dir)
+ print(f"completed_files: {len(completed_files)}")
+
+ # Files that have not been processed yet.
+ incomplete_files = [f for f in caption_files if f not in completed_files]
+ print(f"incomplete_files: {len(incomplete_files)}")
+
+ # Break the loop when there are no incomplete files
+ if len(incomplete_files) == 0:
+ break
+ if len(incomplete_files) <= num_tasks:
+ num_tasks = 1
+
+ # Split tasks into parts.
+ part_len = len(incomplete_files) // num_tasks
+ all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
+ task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
+
+ # Use a pool of workers to process the files in parallel.
+ with Pool() as pool:
+ pool.starmap(annotate, task_args)
+
+ except Exception as e:
+ print(f"Error: {e}")
+
+ # Combine all the processed files into one
+ combined_contents = {}
+ json_path = args.output_json
+
+ # Iterate through json files
+ for file_name in os.listdir(output_dir):
+ if file_name.endswith(".json"):
+ file_path = os.path.join(output_dir, file_name)
+ with open(file_path, "r") as json_file:
+ content = json.load(json_file)
+ combined_contents[file_name[:-5]] = content
+
+ # Write combined content to a json file
+ with open(json_path, "w") as json_file:
+ json.dump(combined_contents, json_file)
+ print("All evaluation completed!")
+
+ # Calculate average score
+ score_sum = 0
+ count = 0
+ for key, result in combined_contents.items():
+ count += 1
+ score_match = result[0]['score']
+ score = int(score_match)
+ score_sum += score
+ average_score = score_sum / count
+
+ print("Average score for consistency:", average_score)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
+ parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
+ parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
+ parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
+ parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
+ parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
+ parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
+ parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
+ args = parser.parse_args()
+
+ # Set the OpenAI API key.
+ os.environ["AZURE_OPENAI_KEY"] = args.api_key
+ os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
+ os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
+
+ client = init()
+
+ main(args)
diff --git a/videollama2/eval/inference_video_cap_msvc.py b/videollama2/eval/inference_video_cap_msvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1b18bbe1833a8278add3715de69c745a4ea39b8
--- /dev/null
+++ b/videollama2/eval/inference_video_cap_msvc.py
@@ -0,0 +1,120 @@
+import math
+import os
+import argparse
+import json
+import warnings
+from tqdm import tqdm
+
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class MSVCDataset(Dataset):
+
+ video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
+
+ def __init__(self, folder, questions, processor):
+ self.folder = folder
+ self.questions = questions
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+
+ video_name = sample['video_path']
+ question = sample['question']
+ answer = sample['captions']
+
+ video_path = os.path.join(self.folder, video_name)
+ video_tensor = self.processor(video_path)
+
+ return {
+ 'video': video_tensor,
+ 'video_name': video_name,
+ 'question': question,
+ 'answer': answer,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ v_id = [x['video_name'] for x in batch]
+ qus = [x['question'] for x in batch]
+ ans = [x['answer'] for x in batch]
+ return vid, v_id, qus, ans
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ model, processor, tokenizer = model_init(args.model_path)
+
+ gt_questions = json.load(open(args.question_file, "r"))
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+
+ answer_file = os.path.join(args.output_file)
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ dataset = MSVCDataset(args.video_folder, gt_questions, processor['video'])
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ # Iterate over each sample in the ground truth file
+ for idx, (video_tensors, video_names, questions, answers) in enumerate(tqdm(dataloader)):
+ video_tensor = video_tensors[0]
+ video_name = video_names[0]
+ question = questions[0]
+ answer = answers[0]
+
+ output = mm_infer(
+ video_tensor,
+ question,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+
+ sample_set = {'video_name': video_name, 'question': question, 'answer': answer, 'pred': output}
+ ans_file.write(json.dumps(sample_set) + "\n")
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--output-file', help='Directory to save the model results JSON.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_mcqa_egoschema.py b/videollama2/eval/inference_video_mcqa_egoschema.py
new file mode 100644
index 0000000000000000000000000000000000000000..387e51407a56e0b2315ec9ffeedb521f0c3b06b5
--- /dev/null
+++ b/videollama2/eval/inference_video_mcqa_egoschema.py
@@ -0,0 +1,153 @@
+import os
+import re
+import math
+import json
+import argparse
+import warnings
+import traceback
+
+from tqdm import tqdm
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class EgoschemaDataset(Dataset):
+
+ video_formats = ['.mp4', '.avi', '.mov', '.mkv']
+
+ def __init__(self, data_folder, data_list, processor):
+ self.data_folder = data_folder
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ line = self.data_list[idx]
+ q_uid = line['q_uid']
+
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(self.data_folder, f"{q_uid}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ video_tensor = self.processor(video_path)
+
+ question = line['question']
+ a0 = line['option 0']
+ a1 = line['option 1']
+ a2 = line['option 2']
+ a3 = line['option 3']
+ a4 = line['option 4']
+ axs = [a0, a1, a2, a3, a4]
+ ops = ['(A)', '(B)', '(C)', '(D)', '(E)']
+
+ instruct = f'Select the best answer to the following multiple-choice question based on the video.\n{question}\nOptions:\n(A) {a0}\n(B) {a1}\n(C) {a2}\n(D) {a3}\n(E) {a4}\nAnswer with the option\'s letter from the given choices directly and only give the best option. The best answer is: '
+
+ return {
+ 'q_uid': q_uid,
+ 'video': video_tensor,
+ 'instruct': instruct,
+ }
+
+
+def build_egoschema_eval(args, processor):
+ questions = json.load(open(args.question_file, "r"))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ dataset = EgoschemaDataset(args.video_folder, questions, processor)
+ dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
+
+ return dataloader
+
+
+def egoschema_dump(ans_file, line, outputs):
+ for idx, output in enumerate(outputs):
+ q_uid = line['q_uid'][idx]
+ instruct = line['instruct'][idx]
+ letters = ['A', 'B', 'C', 'D', 'E']
+
+ output = output.replace('answer', '')
+ output = output.replace('Answer', '')
+ pred_answer = re.findall('[\(\ ]*[A-E][\)\ ]*', output)
+ try:
+
+ assert len(pred_answer) >= 1, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(line['q_uid'], instruct, output)
+ pred_answer = pred_answer[0].strip()
+ pred_answer = pred_answer.strip('()')
+ pred_idx = letters.index(pred_answer)
+ except:
+ traceback.print_exc()
+ pred_idx = 2
+
+ ans_file.write(f'{q_uid}, {pred_idx}\n')
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ model, processor, tokenizer = model_init(args.model_path)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ val_loader = build_egoschema_eval(args, processor['video'])
+
+ # Iterate over each sample in the ground truth file
+ for i, line in enumerate(tqdm(val_loader)):
+ video_tensor = line['video'][0]
+ instruct = line['instruct'][0]
+
+ try:
+ pred = mm_infer(
+ video_tensor,
+ instruct,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+ except:
+ traceback.print_exc()
+ pred = 'C'
+
+ egoschema_dump(ans_file, line, [pred])
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description='Multiple-Choice Video QA Evaluation Script.')
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, default=1)
+ parser.add_argument("--num-workers", type=int, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_mcqa_mvbench.py b/videollama2/eval/inference_video_mcqa_mvbench.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bbdb58be343aac4516b5842c19f49216e2edde3
--- /dev/null
+++ b/videollama2/eval/inference_video_mcqa_mvbench.py
@@ -0,0 +1,203 @@
+import os
+import re
+import math
+import json
+import argparse
+import warnings
+import traceback
+
+import torch
+import numpy as np
+from PIL import Image
+from tqdm import tqdm
+from decord import VideoReader, cpu
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class MVBenchDataset(Dataset):
+
+ def __init__(self, data_list, processor):
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ bound = (None, None)
+ if self.data_list[idx]['bound']:
+ bound = (self.data_list[idx]['data']['start'], self.data_list[idx]['data']['end'])
+ video_path = os.path.join(self.data_list[idx]['prefix'], self.data_list[idx]['data']['video'])
+ torch_imgs = self.processor(video_path, s=bound[0], e=bound[1])
+ question = self.data_list[idx]['data']['question']
+ options = self.data_list[idx]['data']['candidates']
+ answer = self.data_list[idx]['data']['answer']
+ task_type = self.data_list[idx]['task_type']
+
+ answer_idx = -1
+ letters = []
+ options_string = ''
+ for option_idx, c in enumerate(options):
+ letters.append(f"{chr(ord('A') + option_idx)}")
+ options_string += f"({chr(ord('A') + option_idx)}) {c}\n"
+ if c == answer:
+ answer_idx = option_idx
+
+ instruct = f'Question: {question}\nOptions:\n{options_string}Answer with the option\'s letter from the given choices directly and only give the best option.'
+
+ return {
+ 'video': torch_imgs,
+ 'video_path': video_path,
+ 'instruct': instruct,
+ 'letters': letters,
+ 'options': options,
+ 'answer_idx': answer_idx,
+ 'task_type': task_type
+ }
+
+
+tasks = {
+ "Action Sequence": ("action_sequence.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Action Prediction": ("action_prediction.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Action Antonym": ("action_antonym.json", "ssv2_video/", "video", False),
+ "Fine-grained Action": ("fine_grained_action.json", "Moments_in_Time_Raw/videos/", "video", False),
+ "Unexpected Action": ("unexpected_action.json", "FunQA_test/test/", "video", False),
+ "Object Existence": ("object_existence.json", "clevrer/video_validation/", "video", False),
+ "Object Interaction": ("object_interaction.json", "star/Charades_v1_480/", "video", True), # has start & end
+ "Object Shuffle": ("object_shuffle.json", "perception/videos/", "video", False),
+ "Moving Direction": ("moving_direction.json", "clevrer/video_validation/", "video", False),
+ "Action Localization": ("action_localization.json", "sta/sta_video/", "video", True), # has start & end
+ "Scene Transition": ("scene_transition.json", "scene_qa/video/", "video", False),
+ "Action Count": ("action_count.json", "perception/videos/", "video", False),
+ "Moving Count": ("moving_count.json", "clevrer/video_validation/", "video", False),
+ "Moving Attribute": ("moving_attribute.json", "clevrer/video_validation/", "video", False),
+ "State Change": ("state_change.json", "perception/videos/", "video", False),
+ "Fine-grained Pose": ("fine_grained_pose.json", "nturgbd/", "video", False),
+ "Character Order": ("character_order.json", "perception/videos/", "video", False),
+ "Egocentric Navigation": ("egocentric_navigation.json", "vlnqa/", "video", False),
+ "Episodic Reasoning": ("episodic_reasoning.json", "tvqa/frames_fps3_hq/", "frame", True), # has start & end, read frame
+ "Counterfactual Inference": ("counterfactual_inference.json", "clevrer/video_validation/", "video", False),
+}
+
+
+def build_mvbench_eval(args, processor):
+ data_list = []
+ for task_name, task in tasks.items():
+ json_file = os.path.join(args.question_file, task[0])
+ vis_folder = os.path.join(args.video_folder, task[1])
+ with open(json_file, 'r') as f:
+ json_data = json.load(f)
+ for data in json_data:
+ data_list.append({
+ 'task_type': task_name,
+ 'prefix': vis_folder,
+ 'data_type': task[2],
+ 'bound': task[3],
+ 'data': data
+ })
+ data_list = get_chunk(data_list, args.num_chunks, args.chunk_idx)
+ dataset = MVBenchDataset(data_list, processor)
+ dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
+
+ return dataloader
+
+
+def mvbench_dump(vid, instruct, letters, options, output):
+
+ output = output.replace('answer', '')
+ output = output.replace('Answer', '')
+ pred_answer = re.findall(f'[\(,\ ]*[{letters[0]}-{letters[-1]}][\),\ ]*', output)
+ try:
+ find_flag = False
+ if len(pred_answer) == 0:
+ for idx, opt in enumerate(options):
+ # Arabic numerals -> English words
+ if opt.lower() in output.lower():
+ pred_idx = idx
+ find_flag = True
+ break
+ else:
+ pred_answer = pred_answer[0].strip()
+ pred_answer = pred_answer.strip('()')
+ pred_idx = letters.index(pred_answer)
+ find_flag = True
+
+ assert find_flag, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(vid, instruct, output)
+ except:
+ traceback.print_exc()
+ pred_idx = 2
+
+ return pred_idx
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ model, processor, tokenizer = model_init(args.model_path)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ val_loader = build_mvbench_eval(args, processor['video'])
+
+ # NOTE: only support batch size 1 for now
+ for i, line in enumerate(tqdm(val_loader)):
+ vid = line['video_path'][0]
+ video_tensor = line['video'][0]
+ task_type = line['task_type'][0]
+ instruct = line['instruct'][0]
+ letters = list(zip(*line['letters']))[0]
+ options = list(zip(*line['options']))[0]
+ answer_idx = line['answer_idx'][0].item()
+
+ output = mm_infer(
+ video_tensor,
+ instruct,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+
+ pred_idx = mvbench_dump(vid, instruct, letters, options, output)
+
+ ans_file.write(json.dumps({"vid": vid, "task_type": task_type, "pred": pred_idx, "gt": answer_idx}) + '\n')
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, default=1)
+ parser.add_argument("--num-workers", type=int, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py b/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..e562caef4be646a2a30791233bfddc686363f959
--- /dev/null
+++ b/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py
@@ -0,0 +1,169 @@
+import os
+import re
+import math
+import json
+import argparse
+import warnings
+import traceback
+from tqdm import tqdm
+
+import torch
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class PerceptionTestMCQADataset(Dataset):
+
+ video_formats = ['.mp4', '.avi', '.mov', '.mkv']
+
+ def __init__(self, data_list, processor):
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ line = self.data_list[idx]
+ video_name = line['metadata']['video_id']
+ mc_questions = line['mc_question']
+
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ video_tensor = self.processor(video_path)
+
+ instructs = []
+ qids = []
+ ops = []
+ for q in mc_questions:
+ question = q['question']
+ qid = q['id']
+ options = q['options']
+ instruct = f'Question: {question}\nOptions:\n(A) {options[0]}\n(B) {options[1]}\n(C) {options[2]}\nAnswer with the option\'s letter from the given choices directly and only give the best option.'
+
+ instructs.append(instruct)
+ qids.append(qid)
+ ops.append(options)
+
+ return {
+ 'video': video_tensor,
+ 'video_id': video_name,
+ 'instructs': instructs,
+ 'question_ids': qids,
+ 'options': ops,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ v_id = [x['video_id'] for x in batch]
+ ins = [x['instructs'] for x in batch]
+ q_ids = [x['question_ids'] for x in batch]
+ ops = [x['options'] for x in batch]
+ vid = torch.stack(vid, dim=0)
+ return vid, v_id, ins, q_ids, ops
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ model, processor, tokenizer = model_init(args.model_path)
+
+ questions = json.load(open(args.question_file, "r"))
+ questions = list(questions.values())
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ dataset = PerceptionTestMCQADataset(questions, processor['video'])
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ # Iterate over each sample in the ground truth file
+ for i, (video_tensor, video_id, instructs, question_ids, options) in enumerate(tqdm(dataloader)):
+
+ # reduce batch dimension
+ video_tensor = video_tensor[0]
+ video_id = video_id[0]
+ instructs = instructs[0]
+ question_ids = question_ids[0]
+ options = options[0]
+
+ qas = []
+ for idx, instruct in enumerate(instructs):
+ letters = ['(A)', '(B)', '(C)']
+ question_id = question_ids[idx]
+ _options = options[idx]
+
+ output = mm_infer(
+ video_tensor,
+ instruct,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+
+ output = output.replace('answer', '')
+ output = output.replace('Answer', '')
+ pred_answer = re.findall('\(*[A-C]\)*', output)
+ try:
+ assert len(pred_answer) >= 1, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(video_id, instruct, output)
+ pred_answer = pred_answer[0].strip()
+ # if not pred_answer.startswith('('):
+ pred_answer = pred_answer.strip('()')
+ pred_answer = f'({pred_answer})'
+ pred_idx = letters.index(pred_answer)
+ except:
+ traceback.print_exc()
+ tmp_options = [x.lower() for x in _options]
+ if output.lower() in tmp_options:
+ tmp_options = [x.lower() for x in _options]
+ pred_idx = tmp_options.index(output.lower())
+ else:
+ pred_idx = 2
+
+ qas.append({'id': question_id, 'answer_id': pred_idx, 'answer': _options[pred_idx]})
+
+ ans_file.write('\"{}\": {},\n'.format(video_id, json.dumps(qas)))
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--model_max_length", type=int, required=False, default=2048)
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_mcqa_videomme.py b/videollama2/eval/inference_video_mcqa_videomme.py
new file mode 100644
index 0000000000000000000000000000000000000000..249326f643ce8751bc66456a9ba99901bb6e5962
--- /dev/null
+++ b/videollama2/eval/inference_video_mcqa_videomme.py
@@ -0,0 +1,304 @@
+import os
+import re
+import math
+import json
+import copy
+import argparse
+import warnings
+import traceback
+
+import cv2
+import torch
+import pysubs2
+import numpy as np
+import pyarrow.parquet as pq
+from tqdm import tqdm
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+def get_seq_frames(total_num_frames, desired_num_frames):
+ """
+ Calculate the indices of frames to extract from a video.
+
+ Parameters:
+ total_num_frames (int): Total number of frames in the video.
+ desired_num_frames (int): Desired number of frames to extract.
+
+ Returns:
+ list: List of indices of frames to extract.
+ """
+
+ # Calculate the size of each segment from which a frame will be extracted
+ seg_size = float(total_num_frames - 1) / desired_num_frames
+
+ seq = []
+ for i in range(desired_num_frames):
+ # Calculate the start and end indices of each segment
+ start = int(np.round(seg_size * i))
+ end = int(np.round(seg_size * (i + 1)))
+
+ # Append the middle index of the segment to the list
+ seq.append((start + end) // 2)
+
+ return seq
+
+
+class VideoMMEDataset(Dataset):
+
+ video_formats = ['.mp4', '.avi', '.mov', '.mkv']
+
+ def __init__(self, video_folder, subtitle_folder, data_list, processor):
+ self.video_folder = video_folder
+ self.subtitle_folder = subtitle_folder
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ line = self.data_list[idx]
+
+ video_ytid = line['url'].split('watch?v=')[-1]
+
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(self.video_folder, f'{video_ytid}{fmt}')
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ subtitle_path = os.path.join(self.subtitle_folder, f'{video_ytid}.srt')
+
+ try:
+ video_tensor = self.processor(video_path)
+ num_frames = video_tensor.shape[0]
+ except:
+ traceback.print_exc()
+ print(f'It occurs error when reading {video_ytid}')
+ video_tensor = None
+ num_frames = 0
+
+ if video_tensor is not None and os.path.exists(subtitle_path):
+ cv2_vr = cv2.VideoCapture(video_path)
+ duration = int(cv2_vr.get(cv2.CAP_PROP_FRAME_COUNT))
+ fps = cv2_vr.get(cv2.CAP_PROP_FPS)
+ selected_frame_ids = get_seq_frames(duration, num_frames)
+
+ subs = pysubs2.load(subtitle_path, encoding="utf-8")
+ subtitles = []
+ for seleced_frame_id in selected_frame_ids:
+ sub_text = ""
+ cur_time = pysubs2.make_time(fps=fps, frames=seleced_frame_id)
+ for sub in subs:
+ if sub.start < cur_time and sub.end > cur_time:
+ sub_text = sub.text.replace("\\N", " ")
+ break
+ if sub_text.strip():
+ subtitles.append(sub_text)
+ subtitles = "\n".join(subtitles)
+ else:
+ subtitles = ""
+
+ return {
+ 'video': video_tensor,
+ 'subtitle': subtitles,
+ 'record': line,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ sub = [x['subtitle'] for x in batch]
+ rcs = [x['record'] for x in batch]
+ return vid, sub, rcs
+
+
+def load_parquet(parquet_file):
+ table = pq.read_table(parquet_file)
+
+ # Convert PyArrow Table to pandas DataFrame
+ df = table.to_pandas()
+
+ jsons = []
+ for record in df.itertuples():
+
+ if len(jsons) < int(record.video_id):
+ jsons.append({
+ "video_id": record.video_id,
+ "youtube_id": record.videoID,
+ "url": record.url,
+ "duration": record.duration,
+ "domain": record.domain,
+ "sub_category": record.sub_category,
+ "questions": [
+ {
+ "question_id": record.question_id,
+ "task_type": record.task_type,
+ "question": record.question,
+ "choices": list(record.options),
+ "answer": record.answer,
+ }
+ ]
+ })
+ else:
+ jsons[-1]['questions'].append({
+ "question_id": record.question_id,
+ "task_type": record.task_type,
+ "question": record.question,
+ "choices": list(record.options),
+ "answer": record.answer,
+ })
+
+ return jsons
+
+
+def build_videomme_eval(args, processor):
+ # convert parquet to json
+ questions = load_parquet(args.question_file)
+ # questions = json.load(open(args.question_file, "r"))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+ dataset = VideoMMEDataset(args.video_folder, args.subtitle_folder, questions, processor)
+ dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ return dataloader
+
+
+def videomme_dump(record, instruct, options, output):
+ letters = ['A', 'B', 'C', 'D']
+
+ digit2word = {
+ '1': 'one',
+ '2': 'two',
+ '3': 'three',
+ '4': 'four',
+ '5': 'five',
+ '6': 'six',
+ '7': 'seven',
+ '8': 'eight',
+ '9': 'nine',
+ '0': 'zero',
+ }
+
+ output = output.replace('answer', '')
+ output = output.replace('Answer', '')
+ pred_answer = re.findall('[\(\ \[]*([A-D])[\)\.\ \]]*', output)
+ try:
+ find_flag = False
+ if len(pred_answer) == 0:
+ for idx, opt in enumerate(options):
+ # Arabic numerals -> English words
+ opt2 = opt
+ if opt in digit2word:
+ opt2 = digit2word[opt]
+ if opt.lower() in output.lower() or opt2.lower() in output.lower():
+ pred_idx = idx
+ find_flag = True
+ break
+ else:
+ pred_answer = pred_answer[0].strip()
+ pred_answer = pred_answer.strip('()')
+ pred_idx = letters.index(pred_answer)
+ find_flag = True
+
+ assert find_flag, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(record['youtube_id'], instruct, output)
+ except:
+ traceback.print_exc()
+ pred_idx = 2
+
+ return letters[pred_idx]
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ # Initialize the model
+ model, processor, tokenizer = model_init(args.model_path)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ answer_sub_file = answer_file.replace('.json', '_sub.json')
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+ ans_sub_file = open(answer_sub_file, "w")
+
+ val_loader = build_videomme_eval(args, processor['video'])
+
+ # Iterate over each sample in the ground truth file
+ for i, (videos, subtitles, records) in enumerate(tqdm(val_loader)):
+ video_tensor = videos[0]
+ subtitle = subtitles[0]
+ record = records[0]
+
+ new_record = copy.deepcopy(record)
+ new_record_sub = copy.deepcopy(record)
+
+ if video_tensor is None:
+ new_record['missing'] = True
+ ans_file.write(json.dumps(new_record) + ",\n")
+ new_record_sub['missing'] = True
+ ans_sub_file.write(json.dumps(new_record_sub) + ",\n")
+ continue
+ else:
+ new_record['missing'] = False
+ new_record_sub['missing'] = False
+
+ questions = record['questions']
+ for idx, question in enumerate(questions):
+ q = question['question']
+ choices = question['choices']
+ options = [re.findall('[A-D]\. (.*).', c)[0] for c in choices]
+
+ instruct = "Select the best answer to the following multiple-choice question based on the video. Respond with only the letter (A, B, C, or D) of the correct option.\n"
+ instruct += f"{q}\n"
+ for cho_idx, cho in enumerate(choices):
+ instruct += f"{cho}\n"
+ # instruct += "The best option is: "
+ instruct += "Answer with the option\'s letter from the given choices directly and only give the best option. The best answer is: "
+ output = mm_infer(video_tensor, instruct, model=model, tokenizer=tokenizer, modal='video', do_sample=False)
+ new_record['questions'][idx]['response'] = videomme_dump(record, instruct, options, output)
+
+ instruct = f"This video's subtitles are listed below:\n{subtitle}\n" + instruct
+ output = mm_infer(video_tensor, instruct, model=model, tokenizer=tokenizer, modal='video', do_sample=False)
+ new_record_sub['questions'][idx]['response'] = videomme_dump(record, instruct, options, output)
+
+ ans_file.write(json.dumps(new_record) + ",\n")
+ ans_sub_file.write(json.dumps(new_record_sub) + ",\n")
+
+ ans_file.close()
+ ans_sub_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--subtitle-folder', help='Directory containing subtitle files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, default=1)
+ parser.add_argument("--num-workers", type=int, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_oqa_activitynet.py b/videollama2/eval/inference_video_oqa_activitynet.py
new file mode 100644
index 0000000000000000000000000000000000000000..43edf050fa4aa5b72ecc6ac2da29419606640727
--- /dev/null
+++ b/videollama2/eval/inference_video_oqa_activitynet.py
@@ -0,0 +1,150 @@
+import os
+import json
+import math
+import argparse
+import warnings
+import traceback
+from tqdm import tqdm
+
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class ActivitynetDataset(Dataset):
+
+ video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
+
+ def __init__(self, questions, answers, processor):
+ self.questions = questions
+ self.answers = answers
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, idx):
+ sample = self.questions[idx]
+ answer = self.answers[idx]
+
+ video_name = sample['video_name']
+ question = sample['question']
+ question_id = sample['question_id']
+ answer = answer['answer']
+
+ video_path = None
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(args.video_folder, f"v_{video_name}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+ # BUG: compatibility for MSVD, MSRVTT, TGIF
+ temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ if video_path is None:
+ raise FileNotFoundError(f"Video file not found for {os.path.join(args.video_folder, video_name)}")
+
+ video_tensor = self.processor(video_path)
+
+ return {
+ 'video': video_tensor,
+ 'video_name': video_name,
+ 'question': question,
+ 'question_id': question_id,
+ 'answer': answer,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ v_id = [x['video_name'] for x in batch]
+ qus = [x['question'] for x in batch]
+ qid = [x['question_id'] for x in batch]
+ ans = [x['answer'] for x in batch]
+ return vid, v_id, qus, qid, ans
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ # Initialize the model
+ model, processor, tokenizer = model_init(args.model_path)
+
+ gt_questions = json.load(open(args.question_file, "r"))
+ gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
+ gt_answers = json.load(open(args.answer_file, "r"))
+ gt_answers = get_chunk(gt_answers, args.num_chunks, args.chunk_idx)
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ dataset = ActivitynetDataset(gt_questions, gt_answers, processor['video'])
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ answer_file = os.path.join(args.output_file)
+ os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ # Iterate over each sample in the ground truth file
+ for i, (video_tensors, video_names, questions, question_ids, answers) in enumerate(tqdm(dataloader)):
+ video_tensor = video_tensors[0]
+ video_name = video_names[0]
+ question = questions[0]
+ question_id = question_ids[0]
+ answer = answers[0]
+
+ # question = question + '\n' + 'Answer the question using a single word or a short phrase with multiple words.'
+
+ try:
+ output = mm_infer(
+ video_tensor,
+ question,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+ except:
+ traceback.print_exc()
+ output = "error"
+
+ sample_set = {'id': question_id, 'question': question, 'answer': answer, 'pred': output}
+ ans_file.write(json.dumps(sample_set) + "\n")
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument('--output-file', help='Directory to save the model results JSON.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_oqa_vcgpt_consistency.py b/videollama2/eval/inference_video_oqa_vcgpt_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..59b58bba61d4b0d736baab008e024f87f3dbb2b3
--- /dev/null
+++ b/videollama2/eval/inference_video_oqa_vcgpt_consistency.py
@@ -0,0 +1,150 @@
+import os
+import re
+import math
+import json
+import argparse
+import warnings
+from tqdm import tqdm
+
+import torch
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class VCGPTDataset(Dataset):
+
+ video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
+
+ def __init__(self, data_list, processor):
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ line = self.data_list[idx]
+ question1 = line['Q1']
+ question2 = line['Q2']
+ answer = line['A']
+ video_name = line['video_name']
+
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ video_tensor = self.processor(video_path)
+
+ return {
+ 'video': video_tensor,
+ 'video_name': video_name,
+ 'question1': question1,
+ 'question2': question2,
+ 'answer': answer,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ v_id = [x['video_name'] for x in batch]
+ qus1 = [x['question1'] for x in batch]
+ qus2 = [x['question2'] for x in batch]
+ ans = [x['answer'] for x in batch]
+ vid = torch.stack(vid, dim=0)
+ return vid, v_id, qus1, qus2, ans
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ # Initialize the model
+ model, processor, tokenizer = model_init(args.model_path)
+
+ questions = json.load(open(args.question_file, "r"))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ dataset = VCGPTDataset(questions, processor['video'])
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ output_list = [] # List to store the output results
+
+ # Iterate over each sample in the ground truth file
+ for i, (video_tensors, video_names, questions1, questions2, answers) in enumerate(tqdm(dataloader)):
+
+ # reduce batch dimension
+ video_tensor = video_tensors[0]
+ video_name = video_names[0]
+ question1 = questions1[0]
+ question2 = questions2[0]
+ answer = answers[0]
+
+ output1 = mm_infer(
+ video_tensor,
+ question1,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+
+ output2 = mm_infer(
+ video_tensor,
+ question2,
+ model=model,
+ tokenizer=tokenizer,
+ do_sample=False,
+ modal='video',
+ )
+
+ qa = {'video_name': video_name, 'Q1': question1, 'Q2': question2, 'A': answer, 'P1': output1, 'P2': output2}
+
+ ans_file.write(json.dumps(qa) + "\n")
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ # Define the command-line arguments
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--model_base', help='', default=None, type=str, required=False)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--model_max_length", type=int, required=False, default=2048)
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/eval/inference_video_oqa_vcgpt_general.py b/videollama2/eval/inference_video_oqa_vcgpt_general.py
new file mode 100644
index 0000000000000000000000000000000000000000..e30a77fa5776b2940fcfca4a90357cf3acf52d50
--- /dev/null
+++ b/videollama2/eval/inference_video_oqa_vcgpt_general.py
@@ -0,0 +1,130 @@
+import os
+import re
+import math
+import json
+import argparse
+import warnings
+from tqdm import tqdm
+
+import torch
+from torch.utils.data import Dataset, DataLoader
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+
+
+def split_list(lst, n):
+ """Split a list into n (roughly) equal-sized chunks"""
+ chunk_size = math.ceil(len(lst) / n) # integer division
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
+
+
+def get_chunk(lst, n, k):
+ chunks = split_list(lst, n)
+ return chunks[k]
+
+
+class VCGPTDataset(Dataset):
+
+ video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
+
+ def __init__(self, data_list, processor):
+ self.data_list = data_list
+ self.processor = processor
+
+ def __len__(self):
+ return len(self.data_list)
+
+ def __getitem__(self, idx):
+ line = self.data_list[idx]
+ question = line['Q']
+ answer = line['A']
+ video_name = line['video_name']
+
+ for fmt in self.video_formats: # Added this line
+ temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
+ if os.path.exists(temp_path):
+ video_path = temp_path
+ break
+
+ video_tensor = self.processor(video_path)
+
+ return {
+ 'video': video_tensor,
+ 'video_name': video_name,
+ 'question': question,
+ 'answer': answer,
+ }
+
+
+def collate_fn(batch):
+ vid = [x['video'] for x in batch]
+ v_id = [x['video_name'] for x in batch]
+ qus = [x['question'] for x in batch]
+ ans = [x['answer'] for x in batch]
+ vid = torch.stack(vid, dim=0)
+ return vid, v_id, qus, ans
+
+
+def run_inference(args):
+ disable_torch_init()
+
+ # Initialize the model
+ model, processor, tokenizer = model_init(args.model_path)
+
+ questions = json.load(open(args.question_file, "r"))
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
+
+ assert args.batch_size == 1, "Batch size must be 1 for inference"
+ dataset = VCGPTDataset(questions, processor['video'])
+ dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
+
+ answer_file = os.path.expanduser(args.answer_file)
+ os.makedirs(os.path.dirname(answer_file), exist_ok=True)
+ ans_file = open(answer_file, "w")
+
+ # Iterate over each sample in the ground truth file
+ for i, (video_tensors, video_names, questions, answers) in enumerate(tqdm(dataloader)):
+
+ # reduce batch dimension
+ video_tensor = video_tensors[0]
+ video_name = video_names[0]
+ question = questions[0]
+ answer = answers[0]
+
+ output = mm_infer(
+ video_tensor,
+ question,
+ model=model,
+ tokenizer=tokenizer,
+ modal='video',
+ do_sample=False,
+ )
+
+ qa = {'video_name': video_name, 'Q': question, 'A': answer, 'P': output}
+
+ ans_file.write(json.dumps(qa) + "\n")
+
+ ans_file.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--model-path', help='', required=True)
+ parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
+ parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
+ parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
+ parser.add_argument("--num-chunks", type=int, default=1)
+ parser.add_argument("--chunk-idx", type=int, default=0)
+ parser.add_argument("--device", type=str, required=False, default='cuda:0')
+ parser.add_argument("--batch-size", type=int, required=False, default=1)
+ parser.add_argument("--num-workers", type=int, required=False, default=8)
+ args = parser.parse_args()
+
+ run_inference(args)
diff --git a/videollama2/mm_utils.py b/videollama2/mm_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7665d69281a8b8b9726f689da03aff4f0227c67b
--- /dev/null
+++ b/videollama2/mm_utils.py
@@ -0,0 +1,357 @@
+import ast
+import os
+import math
+import base64
+import traceback
+from io import BytesIO
+
+import cv2
+import torch
+import imageio
+import numpy as np
+from PIL import Image
+from decord import VideoReader, cpu
+from moviepy.editor import VideoFileClip
+from transformers import StoppingCriteria
+
+from .constants import NUM_FRAMES, MAX_FRAMES, NUM_FRAMES_PER_SECOND, MODAL_INDEX_MAP, DEFAULT_IMAGE_TOKEN
+
+
+def chunk_list(input_list, chunk_size):
+ return [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)]
+
+
+def load_image_from_base64(image):
+ return Image.open(BytesIO(base64.b64decode(image)))
+
+
+def expand2square(pil_img, background_color):
+ width, height = pil_img.size
+ if width == height:
+ return pil_img
+ elif width > height:
+ result = Image.new(pil_img.mode, (width, width), background_color)
+ result.paste(pil_img, (0, (width - height) // 2))
+ return result
+ else:
+ result = Image.new(pil_img.mode, (height, height), background_color)
+ result.paste(pil_img, ((height - width) // 2, 0))
+ return result
+
+
+def create_photo_grid(arr, rows=None, cols=None):
+ """
+ Create a photo grid from a 4D numpy array with shape [t, h, w, c].
+
+ Parameters:
+ arr (numpy.ndarray): Input array with shape [t, h, w, c].
+ rows (int): Optional. Number of rows in the grid. If not set, it will be determined based on `cols` or the square root of `t`.
+ cols (int): Optional. Number of columns in the grid. If not set, it will be determined based on `rows` or the square root of `t`.
+
+ Returns:
+ numpy.ndarray: A 3D numpy array representing the photo grid.
+ """
+
+ if isinstance(arr, list):
+ if isinstance(arr[0], Image.Image):
+ arr = np.stack([np.array(img) for img in arr])
+ elif isinstance(arr[0], np.ndarray):
+ arr = np.stack(arr)
+ else:
+ raise ValueError("Invalid input type. Expected list of Images or numpy arrays.")
+
+ t, h, w, c = arr.shape
+
+ # Calculate the number of rows and columns if not provided
+ if rows is None and cols is None:
+ rows = math.ceil(math.sqrt(t))
+ cols = math.ceil(t / rows)
+ elif rows is None:
+ rows = math.ceil(t / cols)
+ elif cols is None:
+ cols = math.ceil(t / rows)
+
+ # Check if the grid can hold all the images
+ if rows * cols < t:
+ raise ValueError(f"Not enough grid cells ({rows}x{cols}) to hold all images ({t}).")
+
+ # Create the grid array with appropriate height and width
+ grid_height = h * rows
+ grid_width = w * cols
+ grid = np.zeros((grid_height, grid_width, c), dtype=arr.dtype)
+
+ # Fill the grid with images
+ for i in range(t):
+ row_idx = i // cols
+ col_idx = i % cols
+ grid[row_idx*h:(row_idx+1)*h, col_idx*w:(col_idx+1)*w, :] = arr[i]
+
+ return grid
+
+
+def process_image(image_path, processor, aspect_ratio='pad'):
+ image = Image.open(image_path).convert('RGB')
+
+ images = [np.array(image)]
+
+ if aspect_ratio == 'pad':
+ images = [Image.fromarray(f) for f in images]
+ images = [expand2square(image, tuple(int(x*255) for x in processor.image_mean)) for image in images]
+ else:
+ images = [Image.fromarray(f) for f in images]
+
+ images = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ return images
+
+
+def frame_sample(duration, mode='uniform', num_frames=None, fps=None):
+ if mode == 'uniform':
+ assert num_frames is not None, "Number of frames must be provided for uniform sampling."
+ # NOTE: v1 version
+ # Calculate the size of each segment from which a frame will be extracted
+ seg_size = float(duration - 1) / num_frames
+
+ frame_ids = []
+ for i in range(num_frames):
+ # Calculate the start and end indices of each segment
+ start = seg_size * i
+ end = seg_size * (i + 1)
+ # Append the middle index of the segment to the list
+ frame_ids.append((start + end) / 2)
+
+ return np.round(np.array(frame_ids) + 1e-6).astype(int)
+ # NOTE: v0 version
+ # return np.linspace(0, duration-1, num_frames, dtype=int)
+ elif mode == 'fps':
+ assert fps is not None, "FPS must be provided for FPS sampling."
+ segment_len = min(fps // NUM_FRAMES_PER_SECOND, duration)
+ return np.arange(segment_len // 2, duration, segment_len, dtype=int)
+ else:
+ raise ImportError(f'Unsupported frame sampling mode: {mode}')
+
+
+def process_video(video_path, processor, s=None, e=None, aspect_ratio='pad', num_frames=NUM_FRAMES):
+ if isinstance(video_path, str):
+ if s is not None and e is not None:
+ s = s if s >= 0. else 0.
+ e = e if e >= 0. else 0.
+ if s > e:
+ s, e = e, s
+ elif s == e:
+ e = s + 1
+
+ # 1. Loading Video
+ if os.path.isdir(video_path):
+ frame_files = sorted(os.listdir(video_path))
+
+ fps = 3
+ num_frames_of_video = len(frame_files)
+ elif video_path.endswith('.gif'):
+ gif_reader = imageio.get_reader(video_path)
+
+ fps = 25
+ num_frames_of_video = len(gif_reader)
+ else:
+ vreader = VideoReader(video_path, ctx=cpu(0), num_threads=1)
+
+ fps = vreader.get_avg_fps()
+ num_frames_of_video = len(vreader)
+
+ # 2. Determine frame range & Calculate frame indices
+ f_start = 0 if s is None else max(int(s * fps) - 1, 0)
+ f_end = num_frames_of_video - 1 if e is None else min(int(e * fps) - 1, num_frames_of_video - 1)
+ frame_indices = list(range(f_start, f_end + 1))
+
+ duration = len(frame_indices)
+ # 3. Sampling frame indices
+ if num_frames is None:
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='fps', fps=fps)]
+ else:
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='uniform', num_frames=num_frames)]
+
+ # 4. Acquire frame data
+ if os.path.isdir(video_path):
+ video_data = [Image.open(os.path.join(video_path, frame_files[f_idx])) for f_idx in sampled_frame_indices]
+ elif video_path.endswith('.gif'):
+ video_data = [Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)) for idx, frame in enumerate(gif_reader) if idx in sampled_frame_indices]
+ else:
+ video_data = [Image.fromarray(frame) for frame in vreader.get_batch(sampled_frame_indices).asnumpy()]
+
+ elif isinstance(video_path, np.ndarray):
+ video_data = [Image.fromarray(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], np.ndarray):
+ video_data = [Image.fromarray(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], str):
+ video_data = [Image.open(f) for f in video_path]
+ elif isinstance(video_path, list) and isinstance(video_path[0], Image.Image):
+ video_data = video_path
+ else:
+ raise ValueError(f"Unsupported video path type: {type(video_path)}")
+
+ while num_frames is not None and len(video_data) < num_frames:
+ video_data.append(Image.fromarray(np.zeros((*video_data[-1].size, 3), dtype=np.uint8)))
+
+ # MAX_FRAMES filter
+ video_data = video_data[:MAX_FRAMES]
+
+ if aspect_ratio == 'pad':
+ images = [expand2square(f, tuple(int(x*255) for x in processor.image_mean)) for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ else:
+ images = [f for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ return video
+
+
+def process_video_old(video_path, processor, aspect_ratio='pad', num_frames=NUM_FRAMES, image_grid=False, sample_scheme='uniform'):
+ def frame_sample(duration, mode='uniform', local_fps=None):
+ if mode == 'uniform':
+ # Calculate the size of each segment from which a frame will be extracted
+ seg_size = float(duration - 1) / num_frames
+
+ frame_ids = []
+ for i in range(num_frames):
+ # Calculate the start and end indices of each segment
+ start = int(np.round(seg_size * i))
+ end = int(np.round(seg_size * (i + 1)))
+ # Append the middle index of the segment to the list
+ frame_ids.append((start + end) // 2)
+
+ return frame_ids
+ # NOTE: old version
+ # return np.linspace(0, duration-1, num_frames, dtype=int)
+ elif mode == 'fps':
+ assert local_fps is not None
+ segment_len = min(local_fps // NUM_FRAMES_PER_SECOND, duration)
+ return np.arange(segment_len // 2, duration, segment_len, dtype=int)
+ else:
+ raise ImportError(f'Unsupported frame sampling mode: {mode}')
+
+ if isinstance(video_path, str):
+ if video_path.endswith('.gif'):
+ video_gif = imageio.get_reader(video_path)
+ duration, local_fps = len(video_gif), 10
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ video_data = [frame for index, frame in enumerate(video_gif) if index in frame_id_list]
+ # added by lixin4ever, include the support of .webm files from sthsthv2
+ elif video_path.endswith('.webm'):
+ video_webm = VideoFileClip(video_path)
+ video_frames = np.array(list(video_webm.iter_frames()))
+
+ duration, local_fps = len(video_frames), video_webm.fps
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ video_data = video_frames[frame_id_list]
+ else:
+ # NOTE: num_threads=1 is required to avoid deadlock in multiprocessing
+ decord_vr = VideoReader(uri=video_path, ctx=cpu(0), num_threads=1)
+ duration, local_fps = len(decord_vr), float(decord_vr.get_avg_fps())
+
+ frame_id_list = frame_sample(duration, mode=sample_scheme, local_fps=local_fps)
+ # limit the max input frames
+ if len(frame_id_list) > MAX_FRAMES:
+ frame_id_list = np.linspace(0, duration-1, MAX_FRAMES, dtype=int)
+ try:
+ video_data = decord_vr.get_batch(frame_id_list).numpy()
+ except:
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+
+ elif isinstance(video_path, np.ndarray):
+ assert len(video_path) == num_frames
+ video_data = video_path
+ elif isinstance(video_path, list):
+ assert len(video_path) == num_frames
+ video_data = np.stack([np.array(x) for x in video_path])
+
+ if image_grid:
+ grid_h = grid_w = math.ceil(math.sqrt(num_frames))
+ pg = create_photo_grid(video_data, grid_h, grid_w)
+ video_data = [pg, *video_data]
+
+ if aspect_ratio == 'pad':
+ images = [Image.fromarray(f.numpy() if isinstance(f, torch.Tensor) else f) for f in video_data]
+ images = [expand2square(image, tuple(int(x*255) for x in processor.image_mean)) for image in images]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+ else:
+ images = [Image.fromarray(f.numpy() if isinstance(f, torch.Tensor) else f) for f in video_data]
+ video = processor.preprocess(images, return_tensors='pt')['pixel_values']
+
+ return video
+
+
+def tokenizer_multimodal_token(prompt, tokenizer, multimodal_token=DEFAULT_IMAGE_TOKEN, return_tensors=None):
+ """Tokenize text and multimodal tag to input_ids.
+
+ Args:
+ prompt (str): Text prompt (w/ multimodal tag), e.g., '\nDescribe the video.'
+ tokenizer (transformers.PreTrainedTokenizer): Tokenizer object.
+ multimodal_token (int): Token index corresponding to the multimodal tag.
+ """
+ multimodal_token_index = MODAL_INDEX_MAP.get(multimodal_token, None)
+ if multimodal_token_index is None:
+ input_ids = tokenizer(prompt, add_special_tokens=False).input_ids
+ else:
+ prompt_chunks = [tokenizer(chunk, add_special_tokens=False).input_ids for idx, chunk in enumerate(prompt.split(multimodal_token))]
+
+ input_ids = []
+ for i in range(1, 2 * len(prompt_chunks)):
+ if i % 2 == 1:
+ input_ids.extend(prompt_chunks[i // 2])
+ else:
+ input_ids.append(multimodal_token_index)
+
+ if return_tensors is not None:
+ if return_tensors == 'pt':
+ return torch.tensor(input_ids, dtype=torch.long)
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
+ return input_ids
+
+
+def get_model_name_from_path(model_path):
+ model_path = model_path.strip("/")
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ return model_paths[-2] + "_" + model_paths[-1]
+ else:
+ return model_paths[-1]
+
+
+class KeywordsStoppingCriteria(StoppingCriteria):
+ def __init__(self, keywords, tokenizer, input_ids):
+ self.keywords = keywords
+ self.keyword_ids = []
+ self.max_keyword_len = 0
+ for keyword in keywords:
+ cur_keyword_ids = tokenizer(keyword).input_ids
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
+ cur_keyword_ids = cur_keyword_ids[1:]
+ if len(cur_keyword_ids) > self.max_keyword_len:
+ self.max_keyword_len = len(cur_keyword_ids)
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
+ self.tokenizer = tokenizer
+ self.start_len = input_ids.shape[1]
+
+ def call_for_batch(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
+ for keyword_id in self.keyword_ids:
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
+ return True
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
+ for keyword in self.keywords:
+ if keyword in outputs:
+ return True
+ return False
+
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
+ outputs = []
+ for i in range(output_ids.shape[0]):
+ outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores))
+ return all(outputs)
diff --git a/videollama2/model/__init__.py b/videollama2/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..faab87fa9d4b59ebb9fbd83efc7f013d85b4aba0
--- /dev/null
+++ b/videollama2/model/__init__.py
@@ -0,0 +1,194 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import os
+import warnings
+import shutil
+
+import torch
+from transformers import PretrainedConfig, AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
+
+from .projector import load_mm_projector
+from .videollama2_llama import Videollama2LlamaForCausalLM, Videollama2LlamaConfig
+from .videollama2_mistral import Videollama2MistralForCausalLM, Videollama2MistralConfig
+from .videollama2_mixtral import Videollama2MixtralForCausalLM, Videollama2MixtralConfig
+from .videollama2_qwen2 import Videollama2Qwen2ForCausalLM, Videollama2Qwen2Config
+
+
+VLLMs = {
+ "videollama2": Videollama2MistralForCausalLM,
+ "videollama2_llama": Videollama2LlamaForCausalLM,
+ "videollama2_mistral": Videollama2MistralForCausalLM,
+ "videollama2_mixtral": Videollama2MixtralForCausalLM,
+ "videollama2_qwen2": Videollama2Qwen2ForCausalLM,
+}
+
+VLLMConfigs = {
+ "videollama2": Videollama2MistralConfig,
+ "videollama2_llama": Videollama2LlamaConfig,
+ "videollama2_mistral": Videollama2MistralConfig,
+ "videollama2_mixtral": Videollama2MixtralConfig,
+ "videollama2_qwen2": Videollama2Qwen2Config,
+}
+
+
+def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", use_flash_attn=False, **kwargs):
+ if 'token' in kwargs:
+ token = kwargs['token']
+ else:
+ token = None
+
+ kwargs = {"device_map": device_map, **kwargs}
+
+ if device != "cuda":
+ kwargs['device_map'] = {"": device}
+
+ if load_8bit:
+ kwargs['load_in_8bit'] = True
+ elif load_4bit:
+ # NOTE: High-version Transformers will report: """ValueError: You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing `quantization_config` argument at the same time."""
+ # kwargs['load_in_4bit'] = True
+ kwargs['quantization_config'] = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_compute_dtype=torch.float16,
+ bnb_4bit_use_double_quant=True,
+ bnb_4bit_quant_type='nf4'
+ )
+ else:
+ kwargs['torch_dtype'] = torch.float16
+
+ if use_flash_attn:
+ kwargs['attn_implementation'] = 'flash_attention_2'
+
+ config = AutoConfig.from_pretrained(model_path)
+
+ # judge model type
+ model_type = config.model_type
+
+ # judge pretrain/finetune
+ try:
+ is_pretraining = config.tune_mm_mlp_adapter
+ except:
+ is_pretraining = False
+
+ # NOTE: lora/qlora model loading
+ if 'lora' in model_name.lower() or 'qlora' in model_name.lower():
+ cfg_pretrained = PretrainedConfig.from_pretrained(model_path, token=token)
+ # NOTE: AutoConfig will modify `_name_or_path` property to `model_path` if `model_path` is not None.
+ # cfg_pretrained = AutoConfig.from_pretrained(model_path, token=token)
+ model_base = model_base if model_base is not None else cfg_pretrained._name_or_path
+
+ # NOTE: remove qlora training quantization config
+ if hasattr(config, 'quantization_config'):
+ del config.quantization_config
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False, token=token)
+ print('Loading VideoLLaMA lora model...')
+
+ if 'vicuna' in model_base.lower():
+ model = Videollama2LlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif 'mistral' in model_base.lower():
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
+ if model.lm_head.weight.shape[0] != token_num:
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
+
+ print('Loading additional VideoLLaMA weights...')
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
+ else:
+ # this is probably from HF Hub
+ from huggingface_hub import hf_hub_download
+ def load_from_hf(repo_id, filename, subfolder=None):
+ cache_file = hf_hub_download(
+ repo_id=repo_id,
+ filename=filename,
+ subfolder=subfolder)
+ return torch.load(cache_file, map_location='cpu')
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
+ model.load_state_dict(non_lora_trainables, strict=False)
+
+ from peft import PeftModel
+ print('Loading LoRA weights...')
+ model = PeftModel.from_pretrained(model, model_path)
+ print('Merging LoRA weights...')
+ model = model.merge_and_unload()
+ print('Model is loaded...')
+ elif model_base is not None or is_pretraining:
+ # NOTE: Base/Pretrain model loading
+ print('Loading VideoLLaMA 2 from base model...')
+ cfg_pretrained = PretrainedConfig.from_pretrained(model_path, token=token)
+ # NOTE: AutoConfig will modify `_name_or_path` property to `model_path` if `model_path` is not None.
+ # cfg_pretrained = AutoConfig.from_pretrained(model_path, token=token)
+ model_base = model_base if model_base is not None else cfg_pretrained._name_or_path
+
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False, token=token)
+
+ if model_type in ['videollama2', 'videollama2_mistral']:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_mixtral']:
+ model = Videollama2MixtralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_qwen2']:
+ model = Videollama2Qwen2ForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=config, **kwargs)
+
+ # NOTE; loading vision-language projector
+ # * old codes for loading local mm_projector.bin
+ # mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
+ # mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
+ # model.load_state_dict(mm_projector_weights, strict=False)
+ # * new codes which supports loading mm_projector.bin both offline and online
+ mm_projector_weights = load_mm_projector(model_path, token=token)
+ model.load_state_dict(mm_projector_weights, strict=False)
+ elif 'videollama2' in model_type:
+ # NOTE: SFT model loading
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, token=token)
+
+ if model_type in ['videollama2', 'videollama2_mistral']:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_mixtral']:
+ model = Videollama2MixtralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ elif model_type in ['videollama2_qwen2']:
+ model = Videollama2Qwen2ForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ model = Videollama2MistralForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, config=config, **kwargs)
+ else:
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, token=token)
+ model = AutoModelForCausalLM.from_pretrained(model_path, config=config, **kwargs)
+
+ processor = None
+
+ if "videollama" in model_type:
+ vision_tower = model.get_vision_tower()
+ if not vision_tower.is_loaded:
+ vision_tower.load_model()
+ vision_tower.to(device=device, dtype=torch.float16)
+ # NOTE: videollama2 adopts the same processor for processing image and video.
+ processor = vision_tower.image_processor
+
+ if hasattr(model.config, "max_sequence_length"):
+ context_len = model.config.max_sequence_length
+ else:
+ context_len = 2048
+
+ return tokenizer, model, processor, context_len
diff --git a/videollama2/model/encoder.py b/videollama2/model/encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..399754792c23456261ac97cf961f289a0fe5fa1e
--- /dev/null
+++ b/videollama2/model/encoder.py
@@ -0,0 +1,188 @@
+import os
+
+import torch
+import torch.nn as nn
+
+from transformers import (
+ CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig,
+ SiglipVisionModel, SiglipImageProcessor, SiglipVisionConfig
+)
+
+
+class CLIPVisionTower(nn.Module):
+
+ def __init__(self, vision_tower, args, delay_load=False):
+ super().__init__()
+
+ self.is_loaded = False
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ if not delay_load:
+ self.load_model()
+ else:
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
+
+ def load_model(self):
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
+
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
+ self.vision_tower.requires_grad_(False)
+
+ self.is_loaded = True
+
+ def feature_select(self, image_forward_outs):
+ image_features = image_forward_outs.hidden_states[self.select_layer]
+ if self.select_feature == 'patch':
+ image_features = image_features[:, 1:]
+ elif self.select_feature == 'cls_patch':
+ image_features = image_features
+ else:
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
+ return image_features
+
+ @torch.no_grad()
+ def forward(self, images):
+ if type(images) is list:
+ image_features = []
+ for image in images:
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
+ image_features.append(image_feature)
+ else:
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dummy_feature(self):
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ if self.is_loaded:
+ return self.vision_tower.config
+ else:
+ return self.cfg_only
+
+ @property
+ def hidden_size(self):
+ return self.config.hidden_size
+
+ @property
+ def num_patches(self):
+ return (self.config.image_size // self.config.patch_size) ** 2
+
+ @property
+ def num_patches_per_side(self):
+ return self.config.image_size // self.config.patch_size
+
+ @property
+ def image_size(self):
+ return self.config.image_size
+
+
+class SiglipVisionTower(nn.Module):
+
+ def __init__(self, vision_tower, args, delay_load=False):
+ super().__init__()
+
+ self.is_loaded = False
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ if not delay_load:
+ self.load_model()
+ else:
+ self.cfg_only = SiglipVisionConfig.from_pretrained(self.vision_tower_name)
+
+ def load_model(self):
+ self.image_processor = SiglipImageProcessor.from_pretrained(self.vision_tower_name)
+
+ self.vision_tower = SiglipVisionModel.from_pretrained(self.vision_tower_name)
+ self.vision_tower.requires_grad_(False)
+
+ self.is_loaded = True
+
+ def feature_select(self, image_forward_outs):
+ image_features = image_forward_outs.hidden_states[self.select_layer]
+ if self.select_feature == 'patch':
+ image_features = image_features
+ else:
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
+ return image_features
+
+ @torch.no_grad()
+ def forward(self, images):
+ if type(images) is list:
+ image_features = []
+ for image in images:
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
+ image_features.append(image_feature)
+ else:
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dummy_feature(self):
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ if self.is_loaded:
+ return self.vision_tower.config
+ else:
+ return self.cfg_only
+
+ @property
+ def hidden_size(self):
+ return self.config.hidden_size
+
+ @property
+ def num_patches(self):
+ return (self.config.image_size // self.config.patch_size) ** 2
+
+ @property
+ def num_patches_per_side(self):
+ return self.config.image_size // self.config.patch_size
+
+ @property
+ def image_size(self):
+ return self.config.image_size
+
+
+def build_vision_tower(vision_tower_cfg, **kwargs):
+ vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
+
+ if 'clip' in vision_tower:
+ vision_tower = CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
+ elif 'siglip' in vision_tower:
+ vision_tower = SiglipVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
+ else:
+ raise ValueError(f'Unknown vision tower: {vision_tower}')
+
+ return vision_tower
diff --git a/videollama2/model/projector.py b/videollama2/model/projector.py
new file mode 100644
index 0000000000000000000000000000000000000000..9acddd2f4711f776bf7bf34e77b4be3fba7ca2cb
--- /dev/null
+++ b/videollama2/model/projector.py
@@ -0,0 +1,250 @@
+# Copyright 2024 Alibaba DAMO Academy
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+
+import einops
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from timm.models.regnet import RegStage
+from timm.models.layers import LayerNorm, LayerNorm2d
+from transformers import TRANSFORMERS_CACHE
+
+
+def parse_snapshot_folder(repo_id, cache_dir=None, repo_type="model"):
+ revision = "main"
+ # 1. parse the downloaded cache folder
+ if cache_dir is None:
+ cache_dir = TRANSFORMERS_CACHE
+ else:
+ cache_dir = cache_dir
+ object_id = repo_id.replace("/", "--")
+ repo_cache = os.path.join(cache_dir, f"{repo_type}s--{object_id}")
+ # 2. resolve refs (for instance to convert main to the associated commit sha)
+ refs_dir = os.path.join(repo_cache, "refs")
+ if os.path.isdir(refs_dir):
+ revision_file = os.path.join(refs_dir, revision)
+ if os.path.isfile(revision_file):
+ with open(revision_file) as f:
+ revision = f.read()
+ # 3. acquire the snapshot folder
+ folder = os.path.join(repo_cache, "snapshots", revision)
+
+ return folder
+
+
+def load_mm_projector(model_path, cache_dir=None, token=None):
+ if os.path.exists(os.path.join(model_path, 'mm_projector.bin')):
+ is_local = True
+ folder = model_path
+ else:
+ is_local = False
+ folder = parse_snapshot_folder(model_path, cache_dir=cache_dir, repo_type="model")
+ if not os.path.exists(os.path.join(folder, 'mm_projector.bin')):
+ # downloading from remote repo
+ from huggingface_hub import snapshot_download
+ snapshot_download(repo_id=model_path, cache_dir=cache_dir, token=token)
+
+ mm_projector_weights = torch.load(os.path.join(folder, 'mm_projector.bin'), map_location='cpu')
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
+ return mm_projector_weights
+
+
+class IdentityMap(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x, *args, **kwargs):
+ return x
+
+ @property
+ def config(self):
+ return {"mm_projector_type": 'identity'}
+
+
+class SimpleResBlock(nn.Module):
+
+ def __init__(self, channels):
+ super().__init__()
+ self.pre_norm = nn.LayerNorm(channels)
+
+ self.proj = nn.Sequential(
+ nn.Linear(channels, channels),
+ nn.GELU(),
+ nn.Linear(channels, channels)
+ )
+ def forward(self, x):
+ x = self.pre_norm(x)
+ return x + self.proj(x)
+
+
+def build_vision_projector(config, delay_load=False, **kwargs):
+ projector_type = getattr(config, 'mm_projector_type', 'linear')
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
+ if mlp_gelu_match:
+ mlp_depth = int(mlp_gelu_match.group(1))
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
+ for _ in range(1, mlp_depth):
+ modules.append(nn.GELU())
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
+ return nn.Sequential(*modules)
+
+ if projector_type == "linear":
+ # NOTE: for both linear and mlp2x_gelu projector type, mean pooling is adopted to aggreate video features
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
+ elif projector_type == "stc_connector":
+ return STCConnector(config)
+ elif projector_type == "stp_connector":
+ return STPConnector(config)
+ elif projector_type == "stc_connector_v35":
+ return STCConnectorV35(config)
+ elif projector_type == "spatial_conv":
+ return SpatialConv(config)
+ elif projector_type == "spatial_pool":
+ return SpatialPool(config)
+ if projector_type == 'identity':
+ return IdentityMap()
+
+ raise ValueError(f'Unknown projector type: {projector_type}')
+
+
+def build_mlp(depth, hidden_size, output_hidden_size):
+ modules = [nn.Linear(hidden_size, output_hidden_size)]
+ for _ in range(1, depth):
+ modules.append(nn.GELU())
+ modules.append(nn.Linear(output_hidden_size, output_hidden_size))
+ return nn.Sequential(*modules)
+
+
+class STCConnector(nn.Module):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ """Temporal Convolutional Vision-Language Connector.
+
+ Args:
+ config: config object.
+ downsample: (temporal, height, width) downsample rate.
+ depth: depth of the spatial interaction blocks.
+ mlp_depth: depth of the vision-language projector layers.
+ """
+ super().__init__()
+ self.encoder_hidden_size = encoder_hidden_size = config.mm_hidden_size
+ self.hidden_size = hidden_size = config.hidden_size
+ self.output_hidden_size = output_hidden_size = config.hidden_size
+ # TODO: make these as config arguments
+ self.depth = depth
+ self.mlp_depth = mlp_depth
+ self.downsample = downsample
+ if depth != 0:
+ self.s1 = RegStage(
+ depth=depth,
+ in_chs=encoder_hidden_size,
+ out_chs=hidden_size,
+ stride=1,
+ dilation=1,
+ act_layer=nn.SiLU,
+ norm_layer=LayerNorm2d,
+ )
+ else:
+ self.s1 = nn.Identity()
+ self.sampler = nn.Sequential(
+ nn.Conv3d(
+ in_channels=hidden_size,
+ out_channels=hidden_size,
+ kernel_size=downsample,
+ stride=downsample,
+ padding=1,
+ bias=True
+ ),
+ nn.SiLU()
+ )
+ if depth != 0:
+ self.s2 = RegStage(
+ depth=depth,
+ in_chs=hidden_size,
+ out_chs=hidden_size,
+ stride=1,
+ dilation=1,
+ act_layer=nn.SiLU,
+ norm_layer=LayerNorm2d,
+ )
+ else:
+ self.s2 = nn.Identity()
+ self.readout = build_mlp(mlp_depth, hidden_size, output_hidden_size)
+
+ def forward(self, x):
+ """Aggregate tokens on the temporal and spatial dimensions.
+ Args:
+ x: input tokens [b, t, h, w, d] / [b, t, l, d]
+ Returns:
+ aggregated tokens [b, l, d]
+ """
+ t = x.size(1)
+ if x.ndim == 4:
+ hw = int(x.size(2) ** 0.5)
+ x = einops.rearrange(x, "b t (h w) d -> b d t h w", h=hw, w=hw)
+ elif x.ndim == 5:
+ x = einops.rearrange(x, "b t h w d -> b d t h w")
+
+ x = einops.rearrange(x, "b d t h w -> (b t) d h w")
+ # 1. the first stage of the adapter
+ x = self.s1(x)
+ x = einops.rearrange(x, "(b t) d h w -> b d t h w", t=t)
+ # 2. downsampler
+ x = self.sampler(x)
+ new_t = x.size(2)
+ # 3. the second stage of the adapter
+ x = einops.rearrange(x, "b d t h w -> (b t) d h w")
+ x = self.s2(x)
+ x = einops.rearrange(x, "(b t) d h w -> b (t h w) d", t=new_t)
+ x = self.readout(x)
+ return x
+
+
+class STPConnector(STCConnector):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+ self.sampler = nn.Sequential(nn.AvgPool3d(downsample), nn.SiLU())
+
+
+class STCConnectorV35(STCConnector):
+
+ def __init__(self, config, downsample=(2, 2, 2), depth=4, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+ self.sampler = nn.Sequential(
+ nn.Conv3d(
+ in_channels=self.hidden_size,
+ out_channels=self.hidden_size,
+ kernel_size=downsample,
+ stride=downsample,
+ padding=0,
+ bias=True
+ ),
+ nn.SiLU())
+
+
+class SpatialConv(STCConnector):
+
+ def __init__(self, config, downsample=(1, 2, 2), depth=0, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
+
+
+class SpatialPool(STPConnector):
+
+ def __init__(self, config, downsample=(1, 2, 2), depth=0, mlp_depth=2):
+ super().__init__(config=config, downsample=downsample, depth=depth, mlp_depth=mlp_depth)
diff --git a/videollama2/model/videollama2_arch.py b/videollama2/model/videollama2_arch.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d0c2aef14140a97eec343a6165ffe7b861beb58
--- /dev/null
+++ b/videollama2/model/videollama2_arch.py
@@ -0,0 +1,264 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+from abc import ABC, abstractmethod
+
+import einops
+import torch
+import torch.nn as nn
+
+from .projector import load_mm_projector, build_vision_projector
+from .encoder import build_vision_tower
+from ..constants import IGNORE_INDEX, NUM_FRAMES, MODAL_INDEX_MAP
+
+
+class Videollama2MetaModel:
+
+ def __init__(self, config):
+ super(Videollama2MetaModel, self).__init__(config)
+
+ if hasattr(config, "mm_vision_tower"):
+ self.vision_tower = build_vision_tower(config, delay_load=True)
+ self.mm_projector = build_vision_projector(config)
+
+ def get_vision_tower(self):
+ vision_tower = getattr(self, 'vision_tower', None)
+ if type(vision_tower) is list:
+ vision_tower = vision_tower[0]
+ return vision_tower
+
+ def initialize_vision_modules(self, model_args, fsdp=None):
+ vision_tower = model_args.vision_tower
+ mm_vision_select_layer = model_args.mm_vision_select_layer
+ mm_vision_select_feature = model_args.mm_vision_select_feature
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
+
+ self.config.mm_vision_tower = vision_tower
+
+ if self.get_vision_tower() is None:
+ vision_tower = build_vision_tower(model_args)
+
+ if fsdp is not None and len(fsdp) > 0:
+ self.vision_tower = [vision_tower]
+ else:
+ self.vision_tower = vision_tower
+ else:
+ if fsdp is not None and len(fsdp) > 0:
+ vision_tower = self.vision_tower[0]
+ else:
+ vision_tower = self.vision_tower
+ vision_tower.load_model()
+
+ self.config.use_mm_proj = True
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
+ self.config.mm_hidden_size = vision_tower.hidden_size
+ self.config.mm_vision_select_layer = mm_vision_select_layer
+ self.config.mm_vision_select_feature = mm_vision_select_feature
+
+ if getattr(self, 'mm_projector', None) is None:
+ self.mm_projector = build_vision_projector(self.config)
+ else:
+ # In case it is frozen by LoRA
+ for p in self.mm_projector.parameters():
+ p.requires_grad = True
+
+ if pretrain_mm_mlp_adapter is not None:
+ if os.path.exists(pretrain_mm_mlp_adapter):
+ is_local = True
+ if os.path.isdir(pretrain_mm_mlp_adapter):
+ mm_projector_weights = load_mm_projector(pretrain_mm_mlp_adapter)
+ else:
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
+ else:
+ # Support loading projector weights from remote HuggingFace model hub
+ is_local = False
+ pretrain_mm_mlp_adapter = pretrain_mm_mlp_adapter.replace('mm_projector.bin', '')
+ pretrain_mm_mlp_adapter = pretrain_mm_mlp_adapter.strip('/').strip('\\').strip()
+ mm_projector_weights = load_mm_projector(pretrain_mm_mlp_adapter)
+
+ def get_w(weights, keyword):
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
+
+ # self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
+ # set strict=False to avoid missing key error regarding bert.embeddings.position_ids
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'), strict=False)
+
+
+class Videollama2MetaForCausalLM(ABC):
+
+ @abstractmethod
+ def get_model(self):
+ pass
+
+ def num_frames(self):
+ if hasattr(self.config, 'num_frames'):
+ return self.config.num_frames
+ else:
+ return NUM_FRAMES
+
+ def get_vision_tower(self):
+ return self.get_model().get_vision_tower()
+
+ def encode_images_or_videos(self, images):
+ num_frames = self.config.num_frames if hasattr(self.config, 'num_frames') else NUM_FRAMES
+
+ data_batch = []
+ for i, (data, modal) in enumerate(images):
+ if modal == 'image':
+ data = data.expand(num_frames, -1, -1, -1)
+ else:
+ data = data
+ data_batch.append(data)
+
+ data_batch = torch.stack(data_batch, dim=0)
+
+ assert len(data_batch.size()) == 5
+ batch_size = data_batch.size(0)
+
+ frames = einops.rearrange(data_batch, 'b t c h w -> (b t) c h w')
+ frames_features = self.get_model().get_vision_tower()(frames)
+ frames_features = einops.rearrange(frames_features, '(b t) n h -> b t n h', b = batch_size)
+
+ return self.temporal_aggregator(frames_features)
+
+ def temporal_aggregator(self, frames_features):
+ """Temporal aggregation of frame features.
+ Args:
+ frames_features (torch.Tensor): Frame features with shape (b, t, n, h).
+ Returns:
+ torch.Tensor: Video features with shape (b, n, h).
+ """
+ # TODO: improve the merging method.
+ # *********** mean pooling *************
+ if self.config.mm_projector_type == "mlp2x_gelu" or self.config.mm_projector_type == "linear":
+ video_features = self.get_model().mm_projector(frames_features.mean(1))
+ # *********** spatial convolution *************
+ elif self.config.mm_projector_type == "spatial_conv":
+ video_features = self.get_model().mm_projector(frames_features)
+ # *********** spatial pooling *************
+ elif self.config.mm_projector_type == "spatial_pool":
+ video_features = self.get_model().mm_projector(frames_features)
+ # *********** time ************
+ elif "tc_connector" in self.config.mm_projector_type or "tp_connector" in self.config.mm_projector_type:
+ video_features = self.get_model().mm_projector(frames_features)
+ else:
+ raise Exception(f"Unsupported projector type {self.config.mm_projector_type}!!!")
+
+ return video_features
+
+ def prepare_inputs_labels_for_multimodal(
+ self, input_ids, attention_mask, past_key_values, labels, images
+ ):
+ vision_tower = self.get_vision_tower()
+ # NOTE: text-only situation
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
+ # if past_key_values is not None and vision_tower is not None and Xs is not None and input_ids.shape[1] == 1:
+ # attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
+ return input_ids, attention_mask, past_key_values, None, labels
+
+ mm_features = self.encode_images_or_videos(images)
+
+ new_input_embeds = []
+ new_labels = [] if labels is not None else None
+ cur_mm_idx = 0
+ # replace image/video/audio tokens with pre-computed embeddings
+ for batch_idx, cur_input_ids in enumerate(input_ids):
+ num_multimodals = sum((cur_input_ids == mm_token_idx).sum() for mm_token_idx in MODAL_INDEX_MAP.values())
+ # pure text input
+ if num_multimodals == 0:
+ half_len = cur_input_ids.shape[0] // 2
+ cur_mm_features = mm_features[cur_mm_idx]
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
+ cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_mm_features[0:0], cur_input_embeds_2], dim=0)
+ new_input_embeds.append(cur_input_embeds)
+ if labels is not None:
+ new_labels.append(labels[batch_idx])
+ cur_mm_idx += 1
+ continue
+
+ cur_new_input_embeds = []
+ if labels is not None:
+ cur_labels = labels[batch_idx]
+ cur_new_labels = []
+ assert cur_labels.shape == cur_input_ids.shape
+
+ mm_token_indices = torch.where(sum([cur_input_ids == mm_token_idx for mm_token_idx in MODAL_INDEX_MAP.values()]))[0]
+ while mm_token_indices.numel() > 0:
+ cur_mm_features = mm_features[cur_mm_idx]
+ mm_token_start = mm_token_indices[0]
+
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:mm_token_start]))
+ cur_new_input_embeds.append(cur_mm_features)
+ if labels is not None:
+ cur_new_labels.append(cur_labels[:mm_token_start])
+ cur_new_labels.append(torch.full((cur_mm_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
+ cur_labels = cur_labels[mm_token_start+1:]
+
+ cur_mm_idx += 1
+ cur_input_ids = cur_input_ids[mm_token_start+1:]
+ mm_token_indices = torch.where(sum([cur_input_ids == mm_token_idx for mm_token_idx in MODAL_INDEX_MAP.values()]))[0]
+
+ if cur_input_ids.numel() > 0:
+ cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
+ if labels is not None:
+ cur_new_labels.append(cur_labels)
+ cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
+ # NOTE: one cur_new_input_embeds per each
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
+ new_input_embeds.append(cur_new_input_embeds)
+ if labels is not None:
+ cur_new_labels = torch.cat(cur_new_labels, dim=0)
+ new_labels.append(cur_new_labels)
+
+ # padding
+ if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
+ max_len = max(x.shape[0] for x in new_input_embeds)
+
+ new_input_embeds_align = []
+ for cur_new_embed in new_input_embeds:
+ cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
+ new_input_embeds_align.append(cur_new_embed)
+ new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
+
+ if labels is not None:
+ new_labels_align = []
+ _new_labels = new_labels
+ for cur_new_label in new_labels:
+ cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
+ new_labels_align.append(cur_new_label)
+ new_labels = torch.stack(new_labels_align, dim=0)
+
+ if attention_mask is not None:
+ new_attention_mask = []
+ for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
+ new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
+ new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
+ cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
+ new_attention_mask.append(cur_new_attention_mask)
+ attention_mask = torch.stack(new_attention_mask, dim=0)
+ assert attention_mask.shape == new_labels.shape
+ else:
+ new_input_embeds = torch.stack(new_input_embeds, dim=0)
+ if labels is not None:
+ new_labels = torch.stack(new_labels, dim=0)
+
+ if attention_mask is not None:
+ new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
+ assert attention_mask.shape == new_input_embeds.shape[:2]
+
+ return None, attention_mask, past_key_values, new_input_embeds, new_labels
diff --git a/videollama2/model/videollama2_llama.py b/videollama2/model/videollama2_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..107b9e2ec260ae98526ad1e5b2e46358e69070b1
--- /dev/null
+++ b/videollama2/model/videollama2_llama.py
@@ -0,0 +1,155 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ LlamaConfig, LlamaModel, LlamaForCausalLM
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2LlamaConfig(LlamaConfig):
+ model_type = "videollama2_llama"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_llama"
+
+
+class Videollama2LlamaModel(Videollama2MetaModel, LlamaModel):
+ config_class = Videollama2LlamaConfig
+
+ def __init__(self, config: LlamaConfig):
+ super(Videollama2LlamaModel, self).__init__(config)
+
+
+class Videollama2LlamaForCausalLM(LlamaForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2LlamaConfig
+
+ def __init__(self, config, **kwargs):
+ super(LlamaForCausalLM, self).__init__(config)
+ self.model = Videollama2LlamaModel(config)
+ self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_llama", Videollama2LlamaConfig)
+AutoModelForCausalLM.register(Videollama2LlamaConfig, Videollama2LlamaForCausalLM)
diff --git a/videollama2/model/videollama2_mistral.py b/videollama2/model/videollama2_mistral.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e26b8a3a62e545dd841549b6f0276efa7f15fa3
--- /dev/null
+++ b/videollama2/model/videollama2_mistral.py
@@ -0,0 +1,157 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, PretrainedConfig, \
+ MistralConfig, MistralModel, MistralForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2MistralConfig(MistralConfig):
+ model_type = "videollama2_mistral"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_mistral"
+
+
+class Videollama2MistralModel(Videollama2MetaModel, MistralModel):
+ config_class = Videollama2MistralConfig
+
+ def __init__(self, config: MistralConfig):
+ super(Videollama2MistralModel, self).__init__(config)
+
+
+class Videollama2MistralForCausalLM(MistralForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2MistralConfig
+
+ def __init__(self, config, **kwargs):
+ super(MistralForCausalLM, self).__init__(config)
+ self.model = Videollama2MistralModel(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ outputs = super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ outputs.labels = labels
+
+ return outputs
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_mistral", Videollama2MistralConfig)
+AutoModelForCausalLM.register(Videollama2MistralConfig, Videollama2MistralForCausalLM)
diff --git a/videollama2/model/videollama2_mixtral.py b/videollama2/model/videollama2_mixtral.py
new file mode 100644
index 0000000000000000000000000000000000000000..310bfda04359a477a583fe1c1463be88bef0abc6
--- /dev/null
+++ b/videollama2/model/videollama2_mixtral.py
@@ -0,0 +1,152 @@
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import CrossEntropyLoss
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ MixtralConfig, MixtralModel, MixtralForCausalLM
+
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2MixtralConfig(MixtralConfig):
+ model_type = "videollama2_mixtral"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_mixtral"
+
+
+class Videollama2MixtralModel(Videollama2MetaModel, MixtralModel):
+ config_class = Videollama2MixtralConfig
+
+ def __init__(self, config: MixtralConfig):
+ super(Videollama2MixtralModel, self).__init__(config)
+
+
+class Videollama2MixtralForCausalLM(MixtralForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2MixtralConfig
+
+ def __init__(self, config, **kwargs):
+ super(MixtralForCausalLM, self).__init__(config)
+ self.model = Videollama2MixtralModel(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ return super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_mixtral", Videollama2MixtralConfig)
+AutoModelForCausalLM.register(Videollama2MixtralConfig, Videollama2MixtralForCausalLM)
diff --git a/videollama2/model/videollama2_qwen2.py b/videollama2/model/videollama2_qwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe1c4f45ba5908e2f80002cd6088751d1f8abf2e
--- /dev/null
+++ b/videollama2/model/videollama2_qwen2.py
@@ -0,0 +1,151 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Copyright 2023 Haotian Liu
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from transformers import AutoConfig, AutoModelForCausalLM, \
+ Qwen2Config, Qwen2Model, Qwen2ForCausalLM
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.generation.utils import GenerateOutput
+
+from .videollama2_arch import Videollama2MetaModel, Videollama2MetaForCausalLM
+
+
+class Videollama2Qwen2Config(Qwen2Config):
+ model_type = "videollama2_qwen2"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model_type = "videollama2_qwen2"
+
+
+class Videollama2Qwen2Model(Videollama2MetaModel, Qwen2Model):
+ config_class = Videollama2Qwen2Config
+
+ def __init__(self, config: Videollama2Qwen2Config):
+ super(Videollama2Qwen2Model, self).__init__(config)
+
+
+class Videollama2Qwen2ForCausalLM(Qwen2ForCausalLM, Videollama2MetaForCausalLM):
+ config_class = Videollama2Qwen2Config
+
+ def __init__(self, config, **kwargs):
+ super(Qwen2ForCausalLM, self).__init__(config)
+ self.model = Videollama2Qwen2Model(config)
+ # self.pretraining_tp = config.pretraining_tp
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_model(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ images: Optional[torch.FloatTensor] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ if inputs_embeds is None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ labels
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids,
+ attention_mask,
+ past_key_values,
+ labels,
+ images
+ )
+
+ return super().forward(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ labels=labels,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ images: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ position_ids = kwargs.pop("position_ids", None)
+ attention_mask = kwargs.pop("attention_mask", None)
+ if "inputs_embeds" in kwargs:
+ raise NotImplementedError("`inputs_embeds` is not supported")
+
+ if images is not None:
+ (
+ input_ids,
+ attention_mask,
+ past_key_values,
+ inputs_embeds,
+ _
+ ) = self.prepare_inputs_labels_for_multimodal(
+ input_ids=inputs,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ labels=None,
+ images=images
+ )
+ else:
+ inputs_embeds = self.get_model().embed_tokens(inputs)
+
+ return super().generate(
+ position_ids=position_ids,
+ attention_mask=attention_mask,
+ inputs_embeds=inputs_embeds,
+ **kwargs
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
+ images = kwargs.pop("images", None)
+ _inputs = super().prepare_inputs_for_generation(
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
+ )
+ if images is not None:
+ _inputs['images'] = images
+ return _inputs
+
+
+AutoConfig.register("videollama2_qwen2", Videollama2Qwen2Config)
+AutoModelForCausalLM.register(Videollama2Qwen2Config, Videollama2Qwen2ForCausalLM)
diff --git a/videollama2/serve/README.md b/videollama2/serve/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..6537a2e381d34821e7590866ad9100f7fe62efbb
--- /dev/null
+++ b/videollama2/serve/README.md
@@ -0,0 +1,6 @@
+---
+title: serve
+app_file: gradio_web_server_adhoc.py
+sdk: gradio
+sdk_version: 3.50.0
+---
diff --git a/videollama2/serve/cli.py b/videollama2/serve/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a1fc24a38a9b727392ac74457a896f994891d76
--- /dev/null
+++ b/videollama2/serve/cli.py
@@ -0,0 +1,139 @@
+import argparse
+import torch
+
+from videollama2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, NUM_FRAMES
+from videollama2.conversation import conv_templates, SeparatorStyle
+from videollama2.model.builder import load_pretrained_model
+from videollama2.utils import disable_torch_init
+from videollama2.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, tokenizer_MMODAL_token
+
+from PIL import Image
+from decord import VideoReader, cpu
+
+import requests
+from io import BytesIO
+from transformers import TextStreamer
+
+
+def load_image(image_file):
+ if image_file.startswith('http://') or image_file.startswith('https://'):
+ response = requests.get(image_file)
+ image = Image.open(BytesIO(response.content)).convert('RGB')
+ else:
+ image = Image.open(image_file).convert('RGB')
+ return image
+
+def load_video(video_file):
+ decord_vr = VideoReader(uri=video_file, ctx=cpu(0))
+ duration = len(decord_vr)
+ frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ video = decord_vr.get_batch(frame_id_list)
+ return video
+
+def load_image_or_video(image_or_video_file):
+ if file_path.endswith(('.jpg', '.jpeg', '.png', '.bmp')):
+ return load_image(image_file=image_or_video_file)
+ elif file_path.endswith(('.mp4', '.avi', '.mov')):
+ return load_video(video_file=image_or_video_file)
+ else:
+ raise Exception(f"File type of {image_or_video_file} not supported!!!")
+
+
+def main(args):
+ # Model
+ disable_torch_init()
+
+ model_name = get_model_name_from_path(args.model_path)
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
+
+ # if "llama-2" in model_name.lower():
+ # conv_mode = "llava_llama2"
+ # elif "mistral" in model_name.lower():
+ # conv_mode = "mistral"
+ # elif "v1.6-34b" in model_name.lower():
+ # conv_mode = "chatml_direct"
+ # elif "v1" in model_name.lower():
+ # conv_mode = "llava_v1"
+ # else:
+ # conv_mode = "llava_v0"
+ conv_mode = "llava_v1" # fix conversation mode for now
+
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
+ print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
+ else:
+ args.conv_mode = conv_mode
+
+ conv = conv_templates[args.conv_mode].copy()
+ roles = conv.roles
+
+ image = load_image(args.image_file)
+ image_size = image.size
+ # Similar operation in model_worker.py
+ image_tensor = process_images([image], image_processor, model.config)
+ if type(image_tensor) is list:
+ image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
+ else:
+ image_tensor = image_tensor.to(model.device, dtype=torch.float16)
+
+ while True:
+ try:
+ inp = input(f"{roles[0]}: ")
+ except EOFError:
+ inp = ""
+ if not inp:
+ print("exit...")
+ break
+
+ print(f"{roles[1]}: ", end="")
+
+ if image is not None:
+ # first message
+ if model.config.mm_use_im_start_end:
+ inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
+ else:
+ inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
+ conv.append_message(conv.roles[0], inp)
+ image = None
+ else:
+ # later messages
+ conv.append_message(conv.roles[0], inp)
+ conv.append_message(conv.roles[1], None)
+ prompt = conv.get_prompt()
+
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
+ keywords = [stop_str]
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
+
+ with torch.inference_mode():
+ output_ids = model.generate(
+ input_ids,
+ images=image_tensor,
+ image_sizes=[image_size],
+ do_sample=True if args.temperature > 0 else False,
+ temperature=args.temperature,
+ max_new_tokens=args.max_new_tokens,
+ streamer=streamer,
+ use_cache=True)
+
+ outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
+ conv.messages[-1][-1] = outputs
+
+ if args.debug:
+ print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--image-file", type=str, required=True)
+ parser.add_argument("--device", type=str, default="cuda")
+ parser.add_argument("--conv-mode", type=str, default=None)
+ parser.add_argument("--temperature", type=float, default=0.2)
+ parser.add_argument("--max-new-tokens", type=int, default=512)
+ parser.add_argument("--load-8bit", action="store_true")
+ parser.add_argument("--load-4bit", action="store_true")
+ parser.add_argument("--debug", action="store_true")
+ args = parser.parse_args()
+ main(args)
diff --git a/videollama2/serve/controller.py b/videollama2/serve/controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aeecdf2a4c4da823842d6403cafc3765dbe545a
--- /dev/null
+++ b/videollama2/serve/controller.py
@@ -0,0 +1,298 @@
+"""
+A controller manages distributed workers.
+It sends worker addresses to clients.
+"""
+import argparse
+import asyncio
+import dataclasses
+from enum import Enum, auto
+import json
+import logging
+import time
+from typing import List, Union
+import threading
+
+from fastapi import FastAPI, Request
+from fastapi.responses import StreamingResponse
+import numpy as np
+import requests
+import uvicorn
+
+from videollama2.constants import CONTROLLER_HEART_BEAT_EXPIRATION
+from videollama2.utils import build_logger, server_error_msg
+
+
+logger = build_logger("controller", "controller.log")
+
+
+class DispatchMethod(Enum):
+ LOTTERY = auto()
+ SHORTEST_QUEUE = auto()
+
+ @classmethod
+ def from_str(cls, name):
+ if name == "lottery":
+ return cls.LOTTERY
+ elif name == "shortest_queue":
+ return cls.SHORTEST_QUEUE
+ else:
+ raise ValueError(f"Invalid dispatch method")
+
+
+@dataclasses.dataclass
+class WorkerInfo:
+ model_names: List[str]
+ speed: int
+ queue_length: int
+ check_heart_beat: bool
+ last_heart_beat: str
+
+
+def heart_beat_controller(controller):
+ while True:
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
+ controller.remove_stable_workers_by_expiration()
+
+
+class Controller:
+ def __init__(self, dispatch_method: str):
+ # Dict[str -> WorkerInfo]
+ self.worker_info = {}
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
+
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_controller, args=(self,), daemon=True)
+ self.heart_beat_thread.start()
+
+ logger.info("Init controller")
+
+ def register_worker(self, worker_name: str, check_heart_beat: bool,
+ worker_status: dict):
+ if worker_name not in self.worker_info:
+ logger.info(f"Register a new worker: {worker_name}")
+ else:
+ logger.info(f"Register an existing worker: {worker_name}")
+
+ if not worker_status:
+ worker_status = self.get_worker_status(worker_name)
+ if not worker_status:
+ return False
+
+ self.worker_info[worker_name] = WorkerInfo(
+ worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
+ check_heart_beat, time.time())
+
+ logger.info(f"Register done: {worker_name}, {worker_status}")
+ return True
+
+ def get_worker_status(self, worker_name: str):
+ try:
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
+ except requests.exceptions.RequestException as e:
+ logger.error(f"Get status fails: {worker_name}, {e}")
+ return None
+
+ if r.status_code != 200:
+ logger.error(f"Get status fails: {worker_name}, {r}")
+ return None
+
+ return r.json()
+
+ def remove_worker(self, worker_name: str):
+ del self.worker_info[worker_name]
+
+ def refresh_all_workers(self):
+ old_info = dict(self.worker_info)
+ self.worker_info = {}
+
+ for w_name, w_info in old_info.items():
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
+ logger.info(f"Remove stale worker: {w_name}")
+
+ def list_models(self):
+ model_names = set()
+
+ for w_name, w_info in self.worker_info.items():
+ model_names.update(w_info.model_names)
+
+ return list(model_names)
+
+ def get_worker_address(self, model_name: str):
+ if self.dispatch_method == DispatchMethod.LOTTERY:
+ worker_names = []
+ worker_speeds = []
+ for w_name, w_info in self.worker_info.items():
+ if model_name in w_info.model_names:
+ worker_names.append(w_name)
+ worker_speeds.append(w_info.speed)
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
+ norm = np.sum(worker_speeds)
+ if norm < 1e-4:
+ return ""
+ worker_speeds = worker_speeds / norm
+ if True: # Directly return address
+ pt = np.random.choice(np.arange(len(worker_names)),
+ p=worker_speeds)
+ worker_name = worker_names[pt]
+ return worker_name
+
+ # Check status before returning
+ while True:
+ pt = np.random.choice(np.arange(len(worker_names)),
+ p=worker_speeds)
+ worker_name = worker_names[pt]
+
+ if self.get_worker_status(worker_name):
+ break
+ else:
+ self.remove_worker(worker_name)
+ worker_speeds[pt] = 0
+ norm = np.sum(worker_speeds)
+ if norm < 1e-4:
+ return ""
+ worker_speeds = worker_speeds / norm
+ continue
+ return worker_name
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
+ worker_names = []
+ worker_qlen = []
+ for w_name, w_info in self.worker_info.items():
+ if model_name in w_info.model_names:
+ worker_names.append(w_name)
+ worker_qlen.append(w_info.queue_length / w_info.speed)
+ if len(worker_names) == 0:
+ return ""
+ min_index = np.argmin(worker_qlen)
+ w_name = worker_names[min_index]
+ self.worker_info[w_name].queue_length += 1
+ logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
+ return w_name
+ else:
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
+
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
+ if worker_name not in self.worker_info:
+ logger.info(f"Receive unknown heart beat. {worker_name}")
+ return False
+
+ self.worker_info[worker_name].queue_length = queue_length
+ self.worker_info[worker_name].last_heart_beat = time.time()
+ logger.info(f"Receive heart beat. {worker_name}")
+ return True
+
+ def remove_stable_workers_by_expiration(self):
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
+ to_delete = []
+ for worker_name, w_info in self.worker_info.items():
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
+ to_delete.append(worker_name)
+
+ for worker_name in to_delete:
+ self.remove_worker(worker_name)
+
+ def worker_api_generate_stream(self, params):
+ worker_addr = self.get_worker_address(params["model"])
+ if not worker_addr:
+ logger.info(f"no worker: {params['model']}")
+ ret = {
+ "text": server_error_msg,
+ "error_code": 2,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+ try:
+ response = requests.post(worker_addr + "/worker_generate_stream",
+ json=params, stream=True, timeout=5)
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ yield chunk + b"\0"
+ except requests.exceptions.RequestException as e:
+ logger.info(f"worker timeout: {worker_addr}")
+ ret = {
+ "text": server_error_msg,
+ "error_code": 3,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+ # Let the controller act as a worker to achieve hierarchical
+ # management. This can be used to connect isolated sub networks.
+ def worker_api_get_status(self):
+ model_names = set()
+ speed = 0
+ queue_length = 0
+
+ for w_name in self.worker_info:
+ worker_status = self.get_worker_status(w_name)
+ if worker_status is not None:
+ model_names.update(worker_status["model_names"])
+ speed += worker_status["speed"]
+ queue_length += worker_status["queue_length"]
+
+ return {
+ "model_names": list(model_names),
+ "speed": speed,
+ "queue_length": queue_length,
+ }
+
+
+app = FastAPI()
+
+
+@app.post("/register_worker")
+async def register_worker(request: Request):
+ data = await request.json()
+ controller.register_worker(
+ data["worker_name"], data["check_heart_beat"],
+ data.get("worker_status", None))
+
+
+@app.post("/refresh_all_workers")
+async def refresh_all_workers():
+ models = controller.refresh_all_workers()
+
+
+@app.post("/list_models")
+async def list_models():
+ models = controller.list_models()
+ return {"models": models}
+
+
+@app.post("/get_worker_address")
+async def get_worker_address(request: Request):
+ data = await request.json()
+ addr = controller.get_worker_address(data["model"])
+ return {"address": addr}
+
+
+@app.post("/receive_heart_beat")
+async def receive_heart_beat(request: Request):
+ data = await request.json()
+ exist = controller.receive_heart_beat(
+ data["worker_name"], data["queue_length"])
+ return {"exist": exist}
+
+
+@app.post("/worker_generate_stream")
+async def worker_api_generate_stream(request: Request):
+ params = await request.json()
+ generator = controller.worker_api_generate_stream(params)
+ return StreamingResponse(generator)
+
+
+@app.post("/worker_get_status")
+async def worker_api_get_status(request: Request):
+ return controller.worker_api_get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21001)
+ parser.add_argument("--dispatch-method", type=str, choices=[
+ "lottery", "shortest_queue"], default="shortest_queue")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ controller = Controller(args.dispatch_method)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/examples/1034346401.mp4 b/videollama2/serve/examples/1034346401.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..cb132f0838c45014cdb6f7def631c510fe089293
--- /dev/null
+++ b/videollama2/serve/examples/1034346401.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:08b62a634fe49edc0a19fc53f6ea5cfb345d9b2a6a7047811344c16832dc42b2
+size 1678095
diff --git a/videollama2/serve/examples/desert.jpg b/videollama2/serve/examples/desert.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..926c0b192ff0d2074afbeee5552349cdfc176cc0
Binary files /dev/null and b/videollama2/serve/examples/desert.jpg differ
diff --git a/videollama2/serve/examples/extreme_ironing.jpg b/videollama2/serve/examples/extreme_ironing.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..638b078837f175039b2db49a63821288d9681daa
Binary files /dev/null and b/videollama2/serve/examples/extreme_ironing.jpg differ
diff --git a/videollama2/serve/examples/sample_demo_1.mp4 b/videollama2/serve/examples/sample_demo_1.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..a659cf1dc92142e24909bd17655ac47f9ac433db
--- /dev/null
+++ b/videollama2/serve/examples/sample_demo_1.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fc6562a172eb9cb3c760a3c9992349c1faa2c793c112b7b9e50bd5cb17c2164d
+size 1549315
diff --git a/videollama2/serve/examples/sample_demo_3.mp4 b/videollama2/serve/examples/sample_demo_3.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..17cc120e9fd151e2938cd46c0ba6fd83947bf961
Binary files /dev/null and b/videollama2/serve/examples/sample_demo_3.mp4 differ
diff --git a/videollama2/serve/examples/sample_demo_9.mp4 b/videollama2/serve/examples/sample_demo_9.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..2ddc341888e871212c6f1de05b5745efb8db00aa
Binary files /dev/null and b/videollama2/serve/examples/sample_demo_9.mp4 differ
diff --git a/videollama2/serve/examples/waterview.jpg b/videollama2/serve/examples/waterview.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..6f44ebaba1aa493b8bab3baa4e827b76752b1869
Binary files /dev/null and b/videollama2/serve/examples/waterview.jpg differ
diff --git a/videollama2/serve/gradio_web_server.py b/videollama2/serve/gradio_web_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..2581ccce5240b6be055d963cd6724587fc86d888
--- /dev/null
+++ b/videollama2/serve/gradio_web_server.py
@@ -0,0 +1,499 @@
+import os
+import json
+import time
+import hashlib
+import requests
+import argparse
+import datetime
+
+import numpy as np
+import gradio as gr
+from decord import VideoReader, cpu
+
+from videollama2.constants import LOGDIR, NUM_FRAMES
+from videollama2.conversation import (default_conversation, conv_templates,SeparatorStyle)
+from videollama2.utils import (build_logger, server_error_msg, violates_moderation, moderation_msg)
+
+
+logger = build_logger("gradio_web_server", "gradio_web_server.log")
+
+headers = {"User-Agent": "Videollama2 Client"}
+
+no_change_btn = gr.Button.update()
+enable_btn = gr.Button.update(interactive=True)
+disable_btn = gr.Button.update(interactive=False)
+
+priority = {
+ "vicuna-13b": "aaaaaaa",
+ "koala-13b": "aaaaaab",
+}
+
+
+def get_conv_log_filename():
+ t = datetime.datetime.now()
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
+ return name
+
+
+def get_model_list():
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
+ assert ret.status_code == 200
+ ret = requests.post(args.controller_url + "/list_models")
+ models = ret.json()["models"]
+ models.sort(key=lambda x: priority.get(x, x))
+ logger.info(f"Models: {models}")
+ return models
+
+
+get_window_url_params = """
+function() {
+ const params = new URLSearchParams(window.location.search);
+ url_params = Object.fromEntries(params);
+ console.log(url_params);
+ return url_params;
+ }
+"""
+
+
+def load_demo(url_params, request: gr.Request):
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
+
+ dropdown_update = gr.Dropdown.update(visible=True)
+ if "model" in url_params:
+ model = url_params["model"]
+ if model in models:
+ dropdown_update = gr.Dropdown.update(
+ value=model, visible=True)
+
+ state = default_conversation.copy()
+ return state, dropdown_update
+
+
+def load_demo_refresh_model_list(request: gr.Request):
+ logger.info(f"load_demo. ip: {request.client.host}")
+ models = get_model_list()
+ state = default_conversation.copy()
+ dropdown_update = gr.Dropdown.update(
+ choices=models,
+ value=models[0] if len(models) > 0 else ""
+ )
+ return state, dropdown_update
+
+
+def vote_last_response(state, vote_type, model_selector, request: gr.Request):
+ with open(get_conv_log_filename(), "a") as fout:
+ data = {
+ "tstamp": round(time.time(), 4),
+ "type": vote_type,
+ "model": model_selector,
+ "state": state.dict(),
+ "ip": request.client.host,
+ }
+ fout.write(json.dumps(data) + "\n")
+
+
+def upvote_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"upvote. ip: {request.client.host}")
+ vote_last_response(state, "upvote", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def downvote_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"downvote. ip: {request.client.host}")
+ vote_last_response(state, "downvote", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def flag_last_response(state, model_selector, request: gr.Request):
+ logger.info(f"flag. ip: {request.client.host}")
+ vote_last_response(state, "flag", model_selector, request)
+ return ("",) + (disable_btn,) * 3
+
+
+def regenerate(state, image_process_mode, request: gr.Request):
+ logger.info(f"regenerate. ip: {request.client.host}")
+ state.messages[-1][-1] = None
+ prev_human_msg = state.messages[-2]
+ if type(prev_human_msg[1]) in (tuple, list):
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
+ state.skip_next = False
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def clear_history(request: gr.Request):
+ logger.info(f"clear_history. ip: {request.client.host}")
+ state = default_conversation.copy()
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def add_text_ori(state, text, image, video, image_process_mode, request: gr.Request):
+ # note: imagebox itself is PIL object while videobox is filepath
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
+ if len(text) <= 0 and image is None:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
+ if args.moderate:
+ flagged = violates_moderation(text)
+ if flagged:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
+ no_change_btn,) * 5
+ assert image is None or video is None, "Please don't feed image and video inputs at the same time!!!"
+ text = text[:1536] # Hard cut-off
+ if image is not None:
+ # here image is the PIL object itself
+ text = text[:1200] # Hard cut-off for images
+ if '' not in text:
+ # text = ' ' + text
+ text = text + '\n'
+ text = (text, image, image_process_mode)
+ if len(state.get_images(return_pil=True)) > 0:
+ state = default_conversation.copy()
+ state.modality = "image"
+ if video is not None:
+ print("Video box:", video)
+ # here video is the file path of video
+ text = text[:1200] # Hard cut-off for images
+ if '' not in text:
+ # text = ' ' + text
+ text = text + '\n'
+ text = (text, video, image_process_mode)
+ if len(state.get_videos(return_pil=True)) > 0:
+ state = default_conversation.copy()
+ state.modality = "video"
+ print("Set modality as video...")
+ state.append_message(state.roles[0], text)
+ state.append_message(state.roles[1], None)
+ state.skip_next = False
+ # (state, chatbot, textbox, imagebox, videobox, upvote, downvote, flag, generate, clear)
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def add_text(state, text, image, video, image_process_mode, request: gr.Request):
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
+
+ # if input is new video or image ,reset the state
+ if image is not None or video is not None:
+ state = default_conversation.copy()
+
+ if len(text) <= 0 and image is None and video is None:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), "", None, None) + (no_change_btn,) * 5
+
+ if args.moderate:
+ flagged = violates_moderation(text)
+ if flagged:
+ state.skip_next = True
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (no_change_btn,) * 5
+
+ # process the input video
+ if video is not None:
+ text = text[:1200] #
+ if '' not in text:
+ text = text + '\n'
+ text = (text, video, image_process_mode)
+ state.modality = "video"
+ # process the input image
+ elif image is not None:
+ text = text[:1200] #
+ if '' not in text:
+ text = text + '\n'
+ text = (text, image, image_process_mode)
+ state.modality = "image"
+ elif state.modality == "image" and len(text)>0:
+ state.modality = "image_text"
+ text = text[:1536] # Hard cut-off
+ elif state.modality == "video" and len(text)>0:
+ state.modality = "video_text"
+ text = text[:1536] # Hard cut-off
+
+ state.append_message(state.roles[0], text)
+ state.append_message(state.roles[1], None)
+ state.skip_next = False
+
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5
+
+
+def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
+ logger.info(f"http_bot. ip: {request.client.host}")
+ start_tstamp = time.time()
+ model_name = model_selector
+
+ if state.skip_next:
+ # This generate call is skipped due to invalid inputs
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
+ return
+
+ if len(state.messages) == state.offset + 2:
+ # First round of conversation
+ if "llava" in model_name.lower():
+ if 'llama-2' in model_name.lower():
+ template_name = "llava_llama2"
+ elif "v1" in model_name.lower():
+ if 'mmtag' in model_name.lower():
+ template_name = "v1_mmtag"
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
+ template_name = "v1_mmtag"
+ else:
+ template_name = "llava_v1"
+ else:
+ if 'mmtag' in model_name.lower():
+ template_name = "v0_mmtag"
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
+ template_name = "v0_mmtag"
+ else:
+ template_name = "llava_v0"
+ elif "llama-2" in model_name:
+ template_name = "llama2"
+ else:
+ template_name = "vicuna_v1"
+ template_name = "llava_v1"
+ new_state = conv_templates[template_name].copy()
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
+ new_state.append_message(new_state.roles[1], None)
+ new_state.modality = state.modality
+ state = new_state
+
+ # Query worker address
+ controller_url = args.controller_url
+ ret = requests.post(controller_url + "/get_worker_address",
+ json={"model": model_name})
+ worker_addr = ret.json()["address"]
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
+
+ # No available worker
+ if worker_addr == "":
+ state.messages[-1][-1] = server_error_msg
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+
+ # Construct prompt
+ prompt = state.get_prompt()
+ if state.modality == "image" or state.modality == "image_text":
+ all_images = state.get_images(return_pil=True) # return PIL.Image object
+ elif state.modality == "video" or state.modality == "video_text":
+ all_images = state.get_videos(return_pil=True) # return video frames where each frame is a PIL.Image object
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
+ for idx, (image, hash) in enumerate(zip(all_images, all_image_hash)):
+ t = datetime.datetime.now()
+ if state.modality == "image" or state.modality == "image_text":
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
+ elif state.modality == "video" or state.modality == "video_text":
+ filename = os.path.join(LOGDIR, "serve_videos", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}_{idx}.jpg")
+ if not os.path.isfile(filename):
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+ image.save(filename)
+
+ # Make requests
+ pload = {
+ "model": model_name,
+ "prompt": prompt,
+ "temperature": float(temperature),
+ "top_p": float(top_p),
+ "max_new_tokens": min(int(max_new_tokens), 1536),
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE] else state.sep2,
+ #"images": f'List of {len(state.get_images())} images: {all_image_hash}',
+ "images": f'List of {len(all_image_hash)} images: {all_image_hash}',
+ }
+ logger.info(f"==== request ====\n{pload}")
+
+ if state.modality == "image" or state.modality == "image_text":
+ pload['images'] = state.get_images()
+ elif state.modality == "video" or state.modality == "video_text":
+ pload['images'] = state.get_videos()
+
+ state.messages[-1][-1] = "β"
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
+
+ try:
+ # Stream output
+ response = requests.post(worker_addr + "/worker_generate_stream",
+ headers=headers, json=pload, stream=True, timeout=10)
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ data = json.loads(chunk.decode())
+ if data["error_code"] == 0:
+ output = data["text"][len(prompt):].strip()
+ state.messages[-1][-1] = output + "β"
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
+ else:
+ output = data["text"] + f" (error_code: {data['error_code']})"
+ state.messages[-1][-1] = output
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+ time.sleep(0.03)
+ except requests.exceptions.RequestException as e:
+ state.messages[-1][-1] = server_error_msg
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
+ return
+
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
+
+ finish_tstamp = time.time()
+ logger.info(f"{output}")
+
+ with open(get_conv_log_filename(), "a") as fout:
+ data = {
+ "tstamp": round(finish_tstamp, 4),
+ "type": "chat",
+ "model": model_name,
+ "start": round(start_tstamp, 4),
+ "finish": round(start_tstamp, 4),
+ #"state": state.dict(),
+ "images": all_image_hash,
+ "ip": request.client.host,
+ }
+ fout.write(json.dumps(data) + "\n")
+
+title_markdown = ("""
+# The publicl release of VideoLLaMA2
+""")
+
+tos_markdown = ("""
+### Terms of use
+By using this service, users are required to agree to the following terms:
+The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
+Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
+For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
+""")
+
+
+learn_more_markdown = ("""
+### License
+The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
+""")
+
+block_css = """
+
+#buttons button {
+ min-width: min(120px,100%);
+}
+
+"""
+
+def build_demo(embed_mode):
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
+ with gr.Blocks(title="Video-Llama", theme=gr.themes.Default(), css=block_css) as demo:
+ state = gr.State()
+
+ if not embed_mode:
+ gr.Markdown(title_markdown)
+
+ with gr.Row():
+ with gr.Column(scale=3):
+ with gr.Row(elem_id="model_selector_row"):
+ model_selector = gr.Dropdown(
+ choices=models,
+ value=models[0] if len(models) > 0 else "",
+ interactive=True,
+ show_label=False,
+ container=False)
+
+ imagebox = gr.Image(type="pil")
+ videobox = gr.Video()
+ image_process_mode = gr.Radio(
+ ["Crop", "Resize", "Pad", "Default"],
+ value="Default",
+ label="Preprocess for non-square image", visible=False)
+
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
+ gr.Examples(examples=[
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image?"],
+ [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here?"],
+ [f"{cur_dir}/examples/desert.jpg", "If there are factual errors in the questions, point it out; if not, proceed answering the question. Whatβs happening in the desert?"],
+ ], inputs=[imagebox, textbox], label="Image examples")
+
+ # video example inputs
+ gr.Examples(examples=[
+ [f"{cur_dir}/examples/sample_demo_1.mp4", "Why is this video funny?"],
+ [f"{cur_dir}/examples/sample_demo_3.mp4", "Can you identify any safety hazards in this video?"],
+ [f"{cur_dir}/examples/1034346401.mp4", "What is this young woman doing?"]
+ ], inputs=[videobox, textbox], label="Video examples")
+ #[f"{cur_dir}/examples/sample_demo_9.mp4", "Describe the video in detail and please do not generate repetitive content."]
+
+ with gr.Accordion("Parameters", open=False) as parameter_row:
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
+
+ with gr.Column(scale=8):
+ chatbot = gr.Chatbot(elem_id="chatbot", label="Videollama2 Chatbot", height=550)
+ with gr.Row():
+ with gr.Column(scale=8):
+ textbox.render()
+ with gr.Column(scale=1, min_width=50):
+ submit_btn = gr.Button(value="Send", variant="primary")
+ with gr.Row(elem_id="buttons") as button_row:
+ upvote_btn = gr.Button(value="π Upvote", interactive=False)
+ downvote_btn = gr.Button(value="π Downvote", interactive=False)
+ flag_btn = gr.Button(value="β οΈ Flag", interactive=False)
+ #stop_btn = gr.Button(value="βΉοΈ Stop Generation", interactive=False)
+ regenerate_btn = gr.Button(value="π Regenerate", interactive=False)
+ clear_btn = gr.Button(value="ποΈ Clear", interactive=False)
+
+ if not embed_mode:
+ gr.Markdown(tos_markdown)
+ gr.Markdown(learn_more_markdown)
+ url_params = gr.JSON(visible=False)
+
+ # Register listeners
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
+ upvote_btn.click(upvote_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ downvote_btn.click(downvote_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ flag_btn.click(flag_last_response,
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
+ regenerate_btn.click(regenerate, [state, image_process_mode],
+ [state, chatbot, textbox, imagebox, videobox] + btn_list).then(
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+ clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox, videobox] + btn_list)
+
+ textbox.submit(add_text, [state, textbox, imagebox, videobox, image_process_mode], [state, chatbot, textbox, imagebox, videobox] + btn_list
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+ submit_btn.click(add_text, [state, textbox, imagebox, videobox, image_process_mode], [state, chatbot, textbox, imagebox, videobox] + btn_list
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens],
+ [state, chatbot] + btn_list)
+
+ if args.model_list_mode == "once":
+ demo.load(load_demo, [url_params], [state, model_selector],
+ _js=get_window_url_params)
+ elif args.model_list_mode == "reload":
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector])
+ else:
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
+
+ return demo
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="0.0.0.0")
+ parser.add_argument("--port", type=int)
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
+ parser.add_argument("--concurrency-count", type=int, default=10)
+ parser.add_argument("--model-list-mode", type=str, default="once",
+ choices=["once", "reload"])
+ parser.add_argument("--share", action="store_true")
+ parser.add_argument("--moderate", action="store_true")
+ parser.add_argument("--embed", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ models = get_model_list()
+
+ logger.info(args)
+ demo = build_demo(args.embed)
+ demo.queue(
+ concurrency_count=args.concurrency_count,
+ api_open=False
+ ).launch(
+ server_name=args.host,
+ server_port=args.port,
+ share=args.share
+ )
diff --git a/videollama2/serve/gradio_web_server_adhoc.py b/videollama2/serve/gradio_web_server_adhoc.py
new file mode 100644
index 0000000000000000000000000000000000000000..17da2e644304ceea4fac0632ad3b9c70c4252229
--- /dev/null
+++ b/videollama2/serve/gradio_web_server_adhoc.py
@@ -0,0 +1,318 @@
+import spaces
+
+import os
+import re
+
+import torch
+import gradio as gr
+
+import sys
+sys.path.append('./')
+from videollama2 import model_init, mm_infer
+from videollama2.utils import disable_torch_init
+
+
+title_markdown = ("""
+
+
+
+
+
+
VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs
+ If this demo please you, please give us a star β on Github or π on this space.
+
+
+
+
+
+""")
+
+
+block_css = """
+#buttons button {
+ min-width: min(120px,100%);
+ color: #9C276A
+}
+"""
+
+
+tos_markdown = ("""
+### Terms of use
+By using this service, users are required to agree to the following terms:
+The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
+Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
+For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
+""")
+
+
+learn_more_markdown = ("""
+### License
+This project is released under the Apache 2.0 license as found in the LICENSE file. The service is a research preview intended for non-commercial use ONLY, subject to the model Licenses of LLaMA and Mistral, Terms of Use of the data generated by OpenAI, and Privacy Practices of ShareGPT. Please get in touch with us if you find any potential violations.
+""")
+
+
+plum_color = gr.themes.colors.Color(
+ name='plum',
+ c50='#F8E4EF',
+ c100='#E9D0DE',
+ c200='#DABCCD',
+ c300='#CBA8BC',
+ c400='#BC94AB',
+ c500='#AD809A',
+ c600='#9E6C89',
+ c700='#8F5878',
+ c800='#804467',
+ c900='#713056',
+ c950='#662647',
+)
+
+
+class Chat:
+
+ def __init__(self, model_path, load_8bit=False, load_4bit=False):
+ disable_torch_init()
+
+ self.model, self.processor, self.tokenizer = model_init(model_path, load_8bit=load_8bit, load_4bit=load_4bit)
+
+ @spaces.GPU(duration=120)
+ @torch.inference_mode()
+ def generate(self, data: list, message, temperature, top_p, max_output_tokens):
+ # TODO: support multiple turns of conversation.
+ assert len(data) == 1
+
+ tensor, modal = data[0]
+ response = mm_infer(tensor, message, self.model, self.tokenizer, modal=modal.strip('<>'),
+ do_sample=True if temperature > 0.0 else False,
+ temperature=temperature,
+ top_p=top_p,
+ max_new_tokens=max_output_tokens)
+
+ return response
+
+
+@spaces.GPU(duration=120)
+def generate(image, video, message, chatbot, textbox_in, temperature, top_p, max_output_tokens, dtype=torch.float16):
+ data = []
+
+ processor = handler.processor
+ try:
+ if image is not None:
+ data.append((processor['image'](image).to(handler.model.device, dtype=dtype), ''))
+ elif video is not None:
+ data.append((processor['video'](video).to(handler.model.device, dtype=dtype), ''))
+ elif image is None and video is None:
+ data.append((None, ''))
+ else:
+ raise NotImplementedError("Not support image and video at the same time")
+ except Exception as e:
+ traceback.print_exc()
+ return gr.update(value=None, interactive=True), gr.update(value=None, interactive=True), message, chatbot
+
+ assert len(message) % 2 == 0, "The message should be a pair of user and system message."
+
+ show_images = ""
+ if image is not None:
+ show_images += f' '
+ if video is not None:
+ show_images += f' '
+
+ one_turn_chat = [textbox_in, None]
+
+ # 1. first run case
+ if len(chatbot) == 0:
+ one_turn_chat[0] += "\n" + show_images
+ # 2. not first run case
+ else:
+ # scanning the last image or video
+ length = len(chatbot)
+ for i in range(length - 1, -1, -1):
+ previous_image = re.findall(r' 0:
+ previous_image = previous_image[-1]
+ # 2.1 new image append or pure text input will start a new conversation
+ if (video is not None) or (image is not None and os.path.basename(previous_image) != os.path.basename(image)):
+ message.clear()
+ one_turn_chat[0] += "\n" + show_images
+ break
+ elif len(previous_video) > 0:
+ previous_video = previous_video[-1]
+ # 2.2 new video append or pure text input will start a new conversation
+ if image is not None or (video is not None and os.path.basename(previous_video) != os.path.basename(video)):
+ message.clear()
+ one_turn_chat[0] += "\n" + show_images
+ break
+
+ message.append({'role': 'user', 'content': textbox_in})
+ text_en_out = handler.generate(data, message, temperature=temperature, top_p=top_p, max_output_tokens=max_output_tokens)
+ message.append({'role': 'assistant', 'content': text_en_out})
+
+ one_turn_chat[1] = text_en_out
+ chatbot.append(one_turn_chat)
+
+ return gr.update(value=image, interactive=True), gr.update(value=video, interactive=True), message, chatbot
+
+
+def regenerate(message, chatbot):
+ message.pop(-1), message.pop(-1)
+ chatbot.pop(-1)
+ return message, chatbot
+
+
+def clear_history(message, chatbot):
+ message.clear(), chatbot.clear()
+ return (gr.update(value=None, interactive=True),
+ gr.update(value=None, interactive=True),
+ message, chatbot,
+ gr.update(value=None, interactive=True))
+
+
+# BUG of Zero Environment
+# 1. The environment is fixed to torch>=2.0,<=2.2, gradio>=4.x.x
+# 2. The operation or tensor which requires cuda are limited in those functions wrapped via spaces.GPU
+# 3. The function can't return tensor or other cuda objects.
+
+model_path = 'DAMO-NLP-SG/VideoLLaMA2-7B-16F'
+
+handler = Chat(model_path, load_8bit=False, load_4bit=True)
+
+textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
+
+theme = gr.themes.Default(primary_hue=plum_color)
+# theme.update_color("primary", plum_color.c500)
+theme.set(slider_color="#9C276A")
+theme.set(block_title_text_color="#9C276A")
+theme.set(block_label_text_color="#9C276A")
+theme.set(button_primary_text_color="#9C276A")
+# theme.set(button_secondary_text_color="*neutral_800")
+
+
+with gr.Blocks(title='VideoLLaMA 2 π₯ππ₯', theme=theme, css=block_css) as demo:
+ gr.Markdown(title_markdown)
+ message = gr.State([])
+
+ with gr.Row():
+ with gr.Column(scale=3):
+ image = gr.Image(label="Input Image", type="filepath")
+ video = gr.Video(label="Input Video")
+
+ with gr.Accordion("Parameters", open=True) as parameter_row:
+ # num_beams = gr.Slider(
+ # minimum=1,
+ # maximum=10,
+ # value=1,
+ # step=1,
+ # interactive=True,
+ # label="beam search numbers",
+ # )
+
+ temperature = gr.Slider(
+ minimum=0.1,
+ maximum=1.0,
+ value=0.2,
+ step=0.1,
+ interactive=True,
+ label="Temperature",
+ )
+
+ top_p = gr.Slider(
+ minimum=0.0,
+ maximum=1.0,
+ value=0.7,
+ step=0.1,
+ interactive=True,
+ label="Top P",
+ )
+
+ max_output_tokens = gr.Slider(
+ minimum=64,
+ maximum=1024,
+ value=512,
+ step=64,
+ interactive=True,
+ label="Max output tokens",
+ )
+
+ with gr.Column(scale=7):
+ chatbot = gr.Chatbot(label="VideoLLaMA 2", bubble_full_width=True, height=750)
+ with gr.Row():
+ with gr.Column(scale=8):
+ textbox.render()
+ with gr.Column(scale=1, min_width=50):
+ submit_btn = gr.Button(value="Send", variant="primary", interactive=True)
+ with gr.Row(elem_id="buttons") as button_row:
+ upvote_btn = gr.Button(value="π Upvote", interactive=True)
+ downvote_btn = gr.Button(value="π Downvote", interactive=True)
+ # flag_btn = gr.Button(value="β οΈ Flag", interactive=True)
+ # stop_btn = gr.Button(value="βΉοΈ Stop Generation", interactive=False)
+ regenerate_btn = gr.Button(value="π Regenerate", interactive=True)
+ clear_btn = gr.Button(value="ποΈ Clear history", interactive=True)
+
+ with gr.Row():
+ with gr.Column():
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/examples/extreme_ironing.jpg",
+ "What happens in this image?",
+ ],
+ [
+ f"{cur_dir}/examples/waterview.jpg",
+ "What are the things I should be cautious about when I visit here?",
+ ],
+ [
+ f"{cur_dir}/examples/desert.jpg",
+ "If there are factual errors in the questions, point it out; if not, proceed answering the question. Whatβs happening in the desert?",
+ ],
+ ],
+ inputs=[image, textbox],
+ )
+ with gr.Column():
+ gr.Examples(
+ examples=[
+ [
+ f"{cur_dir}/../../assets/cat_and_chicken.mp4",
+ "What happens in this video?",
+ ],
+ [
+ f"{cur_dir}/../../assets/sora.mp4",
+ "Please describe this video.",
+ ],
+ [
+ f"{cur_dir}/examples/sample_demo_1.mp4",
+ "What does the baby do?",
+ ],
+ ],
+ inputs=[video, textbox],
+ )
+
+ gr.Markdown(tos_markdown)
+ gr.Markdown(learn_more_markdown)
+
+ submit_btn.click(
+ generate,
+ [image, video, message, chatbot, textbox, temperature, top_p, max_output_tokens],
+ [image, video, message, chatbot])
+
+ regenerate_btn.click(
+ regenerate,
+ [message, chatbot],
+ [message, chatbot]).then(
+ generate,
+ [image, video, message, chatbot, textbox, temperature, top_p, max_output_tokens],
+ [image, video, message, chatbot])
+
+ clear_btn.click(
+ clear_history,
+ [message, chatbot],
+ [image, video, message, chatbot, textbox])
+
+demo.launch(share = True)
diff --git a/videollama2/serve/model_worker.py b/videollama2/serve/model_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..236b45c69eee3177196f8af2547db2924bec8121
--- /dev/null
+++ b/videollama2/serve/model_worker.py
@@ -0,0 +1,397 @@
+"""
+A model worker executes the model.
+"""
+import os
+import json
+import time
+import uuid
+import asyncio
+import requests
+import argparse
+import threading
+from threading import Thread
+from functools import partial
+from typing import Iterator, List, Optional, Tuple
+
+import uvicorn
+from fastapi import FastAPI, Request, BackgroundTasks
+from fastapi.responses import StreamingResponse
+
+import torch
+import decord
+import numpy as np
+from PIL import Image
+from decord import VideoReader, cpu
+from transformers import TextIteratorStreamer
+
+from videollama2.constants import WORKER_HEART_BEAT_INTERVAL
+from videollama2.utils import (build_logger, server_error_msg, pretty_print_semaphore)
+from videollama2.model import load_pretrained_model
+from videollama2.mm_utils import process_image, process_video, load_image_from_base64, KeywordsStoppingCriteria, tokenizer_multimodal_token
+from videollama2.mm_utils import chunk_list, frame_sample
+from videollama2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_TOKEN, NUM_FRAMES, MODAL_INDEX_MAP
+
+
+GB = 1 << 30
+
+worker_id = str(uuid.uuid4())[:6]
+logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
+global_counter = 0
+
+model_semaphore = None
+
+
+# variable_content = os.getenv('MY_VARIABLE', '')
+# KEYWORDS_LIST = set(variable_content.split('\n'))
+KEYWORDS_LIST = []
+path = 'assets/keywords.txt'
+if os.path.exists(path):
+ with open(path, 'r', encoding='utf-8') as file:
+ for line in file:
+
+ KEYWORDS_LIST.append(line.strip())
+else:
+ KEYWORDS_LIST = []
+
+
+KEYWORD_BLOCK_MESSAGE2 = "The output contains political, erotic and other unsafe content that violates local laws. Please re-enter your question."
+KEYWORD_BLOCK_MESSAGE1 = "Your input question contains political, erotic and other unsafe content that violates local laws. Please re-enter your question."
+STREAM_CHECK_MULTIPLE = 20
+
+
+def heart_beat_worker(controller):
+
+ while True:
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
+ controller.send_heart_beat()
+
+
+def safety_check(text, history=None, ) -> Optional[str]:
+
+ if len(KEYWORDS_LIST) > 0 and any(x in text.lower() for x in KEYWORDS_LIST):
+ print('############')
+ return KEYWORD_BLOCK_MESSAGE2
+
+ return None
+
+
+def input_safety_check(text) -> Optional[str]:
+ if len(KEYWORDS_LIST) > 0 and any(x in text.lower() for x in KEYWORDS_LIST):
+ print('######## Input keyword alarm triggered:', text)
+ return KEYWORD_BLOCK_MESSAGE1
+ return None
+
+
+class ModelWorker:
+
+ def __init__(self, controller_addr, worker_addr,
+ worker_id, no_register,
+ model_path, model_base, model_name,
+ load_8bit, load_4bit, device):
+ self.controller_addr = controller_addr
+ self.worker_addr = worker_addr
+ self.worker_id = worker_id
+ self.model_path = model_path
+ if model_path.endswith("/"):
+ model_path = model_path[:-1]
+ if model_name is None:
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
+ else:
+ self.model_name = model_paths[-1]
+ else:
+ self.model_name = model_name
+
+ self.device = device
+ logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
+ model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device)
+ self.is_multimodal = 'videollama2' in self.model_name.lower() or 'vlb' in self.model_name.lower()
+
+ if not no_register:
+ self.register_to_controller()
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_worker, args=(self,))
+ self.heart_beat_thread.start()
+
+ def register_to_controller(self):
+ logger.info("Register to controller")
+
+ url = self.controller_addr + "/register_worker"
+ data = {
+ "worker_name": self.worker_addr,
+ "check_heart_beat": True,
+ "worker_status": self.get_status()
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
+
+ def send_heart_beat(self):
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
+ f"global_counter: {global_counter}")
+
+ url = self.controller_addr + "/receive_heart_beat"
+
+ while True:
+ try:
+ ret = requests.post(url, json={
+ "worker_name": self.worker_addr,
+ "queue_length": self.get_queue_length()}, timeout=5)
+ exist = ret.json()["exist"]
+ break
+ except requests.exceptions.RequestException as e:
+ logger.error(f"heart beat error: {e}")
+ time.sleep(5)
+
+ if not exist:
+ self.register_to_controller()
+
+ def get_queue_length(self):
+ if model_semaphore is None:
+ return 0
+ else:
+ return args.limit_model_concurrency - model_semaphore._value + (len(
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
+
+ def get_status(self):
+ return {
+ "model_names": [self.model_name],
+ "speed": 1,
+ "queue_length": self.get_queue_length(),
+ }
+
+ @torch.inference_mode()
+ def generate_stream(self, params):
+ tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
+
+ prompt = params["prompt"]
+ ori_prompt = prompt
+ images_or_videos = params.get("images", None)
+ #print("Input images:", images_or_videos)
+ num_image_tokens = 0
+ modal_list = []
+ if images_or_videos is not None and len(images_or_videos) and self.is_multimodal:
+ if len(images_or_videos) > 0:
+ if len(images_or_videos) != prompt.count(DEFAULT_IMAGE_TOKEN) and len(images_or_videos) != (prompt.count(DEFAULT_VIDEO_TOKEN)):
+ raise ValueError("Number of images/videos does not match number of / tokens in prompt")
+
+ try:
+ print("Load image...")
+ images_or_videos = [load_image_from_base64(image) for image in images_or_videos]
+ images_or_videos = process_image(images_or_videos, image_processor, model.config)
+
+ modal_list = ["image"]
+ replace_token = DEFAULT_IMAGE_TOKEN
+ modal_token_index = MODAL_INDEX_MAP["IMAGE"]
+ except:
+ print("Load video instead...")
+ decord_vr = VideoReader(uri=images_or_videos[0], ctx=cpu(0))
+ duration = len(decord_vr)
+ if not "use_taug" in self.model_path:
+ frame_id_list = np.linspace(0, duration-1, 8, dtype=int)
+ video_frames = decord_vr.get_batch(frame_id_list).asnumpy()
+ images_or_videos = process_video(video_frames, image_processor, model.config)
+ else:
+ print("Temporal augmentation activated!!!")
+ frame_id_list = np.linspace(0, duration-1, 8 * 2 * 2, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list)
+ video_frames = [Image.fromarray(f) for f in video_data.asnumpy()]
+ chunked_video_frames = chunk_list(video_frames, 2*2)
+ expanded_video_frames = [frame_sample(frame_list, 2) for frame_list in chunked_video_frames]
+ images_or_videos = process_video(expanded_video_frames, image_processor, model.config)
+
+ # frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
+ # images_or_videos = decord_vr.get_batch(frame_id_list).asnumpy()
+ # images_or_videos = process_video(images_or_videos, image_processor, model.config)
+ #print("images_or_videos.shape:", images_or_videos.shape)
+ modal_list = ["video"]
+ replace_token = DEFAULT_VIDEO_TOKEN
+ modal_token_index = MODAL_INDEX_MAP["VIDEO"]
+
+ if type(images_or_videos) is list:
+ images_or_videos = [image.to(self.model.device, dtype=torch.float16) for image in images_or_videos]
+ else:
+ images_or_videos = images_or_videos.to(self.model.device, dtype=torch.float16)
+ if modal_list[0] == "video":
+ print("Video:", images_or_videos.shape)
+ images_or_videos = [images_or_videos]
+ else:
+ print("Image:", images_or_videos.shape)
+
+
+ #image_sizes = [image.size for image in images_or_videos]
+
+
+ # if len(images_or_videos) % NUM_FRAMES == 0:
+ # images_or_videos = process_image(images_or_videos, image_processor, model.config)
+ # #images_or_videos = [image.to(self.model.device, dtype=torch.float16) for image in images_or_videos]
+ # #modal_list = ["image"] * len(images_or_videos)
+ # images_or_videos = images_or_videos.to(self.model.device, dtype=torch.float16)
+ # modal_list = ["video"]
+ # replace_token = DEFAULT_VIDEO_TOKEN
+ # else:
+
+ if getattr(self.model.config, 'mm_use_im_start_end', False):
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
+
+ num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
+ else:
+ images = None
+ modal_list = []
+ image_args = {"images_or_videos": images_or_videos, "modal_list": modal_list}
+ else:
+ images = None
+ image_args = {}
+ print("image_args:", image_args)
+ temperature = float(params.get("temperature", 1.0))
+ top_p = float(params.get("top_p", 1.0))
+ max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
+ stop_str = params.get("stop", None)
+ do_sample = True if temperature > 0.001 else False
+
+ #input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
+ # tokenizer for our video-llama beta
+ input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token_index, return_tensors='pt').unsqueeze(0).to(self.device)
+ #print("Current prompt:", prompt)
+ #print("input_ids.shape:", input_ids.shape)
+ keywords = [stop_str]
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
+
+ max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
+
+ if max_new_tokens < 1:
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
+ return
+
+ thread = Thread(target=model.generate, kwargs=dict(
+ inputs=input_ids,
+ do_sample=do_sample,
+ temperature=temperature,
+ top_p=top_p,
+ max_new_tokens=max_new_tokens,
+ streamer=streamer,
+ stopping_criteria=[stopping_criteria],
+ use_cache=True,
+ **image_args
+ ))
+ thread.start()
+
+ generated_text = ori_prompt
+ token_count = 0
+ for new_text in streamer:
+ generated_text += new_text
+ token_count += len(tokenizer.encode(new_text))
+ if token_count >= STREAM_CHECK_MULTIPLE:
+ safety_message = safety_check(generated_text)
+ if safety_message:
+ print('####### Keyword alarm triggered:', generated_text)
+ yield json.dumps({"text": safety_message , "error_code": 1}).encode() + b"\0"
+ return
+ token_count = 0 #
+
+
+ if generated_text.endswith(stop_str):
+ generated_text = generated_text[:-len(stop_str)]
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
+
+ def generate_stream_gate(self, params):
+ try:
+ input_text = params.get("prompt", "")
+ safety_message = input_safety_check(input_text)
+ if safety_message:
+ yield json.dumps({"text": safety_message, "error_code": 1}).encode() + b"\0"
+ return
+
+ for x in self.generate_stream(params):
+ yield x
+ except ValueError as e:
+ print("Caught ValueError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except torch.cuda.CudaError as e:
+ print("Caught torch.cuda.CudaError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except Exception as e:
+ print("Caught Unknown Error", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+app = FastAPI()
+
+
+def release_model_semaphore(fn=None):
+ model_semaphore.release()
+ if fn is not None:
+ fn()
+
+
+@app.post("/worker_generate_stream")
+async def generate_stream(request: Request):
+ global model_semaphore, global_counter
+ global_counter += 1
+ params = await request.json()
+
+ if model_semaphore is None:
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
+ await model_semaphore.acquire()
+ worker.send_heart_beat()
+ generator = worker.generate_stream_gate(params)
+ background_tasks = BackgroundTasks()
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
+ return StreamingResponse(generator, background=background_tasks)
+
+
+@app.post("/worker_get_status")
+async def get_status(request: Request):
+ return worker.get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21002)
+ parser.add_argument("--worker-address", type=str, default="http://localhost:21002")
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
+ parser.add_argument("--model-base", type=str, default=None)
+ parser.add_argument("--model-name", type=str)
+ parser.add_argument("--device", type=str, default="cuda")
+ parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
+ parser.add_argument("--stream-interval", type=int, default=1)
+ parser.add_argument("--no-register", action="store_true")
+ parser.add_argument("--load-8bit", action="store_true")
+ parser.add_argument("--load-4bit", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ if args.multi_modal:
+ logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
+
+ worker = ModelWorker(args.controller_address,
+ args.worker_address,
+ worker_id,
+ args.no_register,
+ args.model_path,
+ args.model_base,
+ args.model_name,
+ args.load_8bit,
+ args.load_4bit,
+ args.device)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/register_worker.py b/videollama2/serve/register_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2c40295e0351f25709ba25554c9329f15bf0d2
--- /dev/null
+++ b/videollama2/serve/register_worker.py
@@ -0,0 +1,26 @@
+"""
+Manually register workers.
+
+Usage:
+python3 -m fastchat.serve.register_worker --controller http://localhost:21001 --worker-name http://localhost:21002
+"""
+
+import argparse
+
+import requests
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--controller-address", type=str)
+ parser.add_argument("--worker-name", type=str)
+ parser.add_argument("--check-heart-beat", action="store_true")
+ args = parser.parse_args()
+
+ url = args.controller_address + "/register_worker"
+ data = {
+ "worker_name": args.worker_name,
+ "check_heart_beat": args.check_heart_beat,
+ "worker_status": None,
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
diff --git a/videollama2/serve/sglang_worker.py b/videollama2/serve/sglang_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3297b7c295abddedfaac7f6fbe882d7b672487d
--- /dev/null
+++ b/videollama2/serve/sglang_worker.py
@@ -0,0 +1,244 @@
+"""
+A model worker executes the model.
+"""
+import argparse
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import json
+import time
+import threading
+import uuid
+
+from fastapi import FastAPI, Request, BackgroundTasks
+from fastapi.responses import StreamingResponse
+import requests
+import re
+import uvicorn
+from functools import partial
+
+from llava.constants import WORKER_HEART_BEAT_INTERVAL
+from llava.utils import (build_logger, server_error_msg,
+ pretty_print_semaphore)
+from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, expand2square
+from llava.constants import DEFAULT_IMAGE_TOKEN
+
+import sglang as sgl
+from sglang.backend.runtime_endpoint import RuntimeEndpoint
+
+
+GB = 1 << 30
+
+worker_id = str(uuid.uuid4())[:6]
+logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
+global_counter = 0
+
+model_semaphore = None
+
+
+def heart_beat_worker(controller):
+ while True:
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
+ controller.send_heart_beat()
+
+
+@sgl.function
+def pipeline(s, prompt, max_tokens):
+ for p in prompt:
+ if type(p) is str:
+ s += p
+ else:
+ s += sgl.image(p)
+ s += sgl.gen("response", max_tokens=max_tokens)
+
+
+class ModelWorker:
+ def __init__(self, controller_addr, worker_addr, sgl_endpoint,
+ worker_id, no_register, model_name):
+ self.controller_addr = controller_addr
+ self.worker_addr = worker_addr
+ self.worker_id = worker_id
+
+ # Select backend
+ backend = RuntimeEndpoint(sgl_endpoint)
+ sgl.set_default_backend(backend)
+ model_path = backend.model_info["model_path"]
+
+ if model_path.endswith("/"):
+ model_path = model_path[:-1]
+ if model_name is None:
+ model_paths = model_path.split("/")
+ if model_paths[-1].startswith('checkpoint-'):
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
+ else:
+ self.model_name = model_paths[-1]
+ else:
+ self.model_name = model_name
+
+ logger.info(f"Loading the SGLANG model {self.model_name} on worker {worker_id} ...")
+
+ if not no_register:
+ self.register_to_controller()
+ self.heart_beat_thread = threading.Thread(
+ target=heart_beat_worker, args=(self,), daemon=True)
+ self.heart_beat_thread.start()
+
+ def register_to_controller(self):
+ logger.info("Register to controller")
+
+ url = self.controller_addr + "/register_worker"
+ data = {
+ "worker_name": self.worker_addr,
+ "check_heart_beat": True,
+ "worker_status": self.get_status()
+ }
+ r = requests.post(url, json=data)
+ assert r.status_code == 200
+
+ def send_heart_beat(self):
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
+ f"global_counter: {global_counter}")
+
+ url = self.controller_addr + "/receive_heart_beat"
+
+ while True:
+ try:
+ ret = requests.post(url, json={
+ "worker_name": self.worker_addr,
+ "queue_length": self.get_queue_length()}, timeout=5)
+ exist = ret.json()["exist"]
+ break
+ except requests.exceptions.RequestException as e:
+ logger.error(f"heart beat error: {e}")
+ time.sleep(5)
+
+ if not exist:
+ self.register_to_controller()
+
+ def get_queue_length(self):
+ if model_semaphore is None:
+ return 0
+ else:
+ return args.limit_model_concurrency - model_semaphore._value + (len(
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
+
+ def get_status(self):
+ return {
+ "model_names": [self.model_name],
+ "speed": 1,
+ "queue_length": self.get_queue_length(),
+ }
+
+ async def generate_stream(self, params):
+ ori_prompt = prompt = params["prompt"]
+ images = params.get("images", None)
+ if images is not None and len(images) > 0:
+ if len(images) > 0:
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
+ raise ValueError("Number of images does not match number of tokens in prompt")
+
+ images = [load_image_from_base64(image) for image in images]
+
+ # FIXME: for image-start/end token
+ # replace_token = DEFAULT_IMAGE_TOKEN
+ # if getattr(self.model.config, 'mm_use_im_start_end', False):
+ # replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
+ # prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
+ prompt = prompt.replace(' ' + DEFAULT_IMAGE_TOKEN + '\n', DEFAULT_IMAGE_TOKEN)
+ prompt_split = prompt.split(DEFAULT_IMAGE_TOKEN)
+ prompt = []
+ for i in range(len(prompt_split)):
+ prompt.append(prompt_split[i])
+ if i < len(images):
+ prompt.append(images[i])
+ else:
+ prompt = [prompt]
+
+ temperature = float(params.get("temperature", 1.0))
+ top_p = float(params.get("top_p", 1.0))
+ # max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
+ stop_str = params.get("stop", None)
+ stop_str = [stop_str] if stop_str is not None else None
+
+ print({'prompt': prompt, 'max_new_tokens': max_new_tokens, 'temperature': temperature, 'top_p': top_p})
+ state = pipeline.run(prompt, max_new_tokens, temperature=temperature, top_p=top_p, stream=True)
+
+ generated_text = ori_prompt
+ async for text_outputs in state.text_async_iter(var_name="response"):
+ generated_text += text_outputs
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
+
+ async def generate_stream_gate(self, params):
+ try:
+ async for x in self.generate_stream(params):
+ yield x
+ except ValueError as e:
+ print("Caught ValueError:", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+ except Exception as e:
+ print("Caught Unknown Error", e)
+ ret = {
+ "text": server_error_msg,
+ "error_code": 1,
+ }
+ yield json.dumps(ret).encode() + b"\0"
+
+
+app = FastAPI()
+
+
+def release_model_semaphore(fn=None):
+ model_semaphore.release()
+ if fn is not None:
+ fn()
+
+
+@app.post("/worker_generate_stream")
+async def generate_stream(request: Request):
+ global model_semaphore, global_counter
+ global_counter += 1
+ params = await request.json()
+
+ if model_semaphore is None:
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
+ await model_semaphore.acquire()
+ worker.send_heart_beat()
+ generator = worker.generate_stream_gate(params)
+ background_tasks = BackgroundTasks()
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
+ return StreamingResponse(generator, background=background_tasks)
+
+
+@app.post("/worker_get_status")
+async def get_status(request: Request):
+ return worker.get_status()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--host", type=str, default="localhost")
+ parser.add_argument("--port", type=int, default=21002)
+ parser.add_argument("--worker-address", type=str,
+ default="http://localhost:21002")
+ parser.add_argument("--controller-address", type=str,
+ default="http://localhost:21001")
+ parser.add_argument("--model-name", type=str)
+ parser.add_argument("--sgl-endpoint", type=str)
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
+ parser.add_argument("--stream-interval", type=int, default=1)
+ parser.add_argument("--no-register", action="store_true")
+ args = parser.parse_args()
+ logger.info(f"args: {args}")
+
+ worker = ModelWorker(args.controller_address,
+ args.worker_address,
+ args.sgl_endpoint,
+ worker_id,
+ args.no_register,
+ args.model_name)
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
diff --git a/videollama2/serve/test_message.py b/videollama2/serve/test_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b090faed0e630b03b2294545050f1f4f5032cad
--- /dev/null
+++ b/videollama2/serve/test_message.py
@@ -0,0 +1,62 @@
+import argparse
+import json
+
+import requests
+
+from llava.conversation import default_conversation
+
+
+def main():
+ if args.worker_address:
+ worker_addr = args.worker_address
+ else:
+ controller_addr = args.controller_address
+ ret = requests.post(controller_addr + "/refresh_all_workers")
+ ret = requests.post(controller_addr + "/list_models")
+ models = ret.json()["models"]
+ models.sort()
+ print(f"Models: {models}")
+
+ ret = requests.post(controller_addr + "/get_worker_address",
+ json={"model": args.model_name})
+ worker_addr = ret.json()["address"]
+ print(f"worker_addr: {worker_addr}")
+
+ if worker_addr == "":
+ return
+
+ conv = default_conversation.copy()
+ conv.append_message(conv.roles[0], args.message)
+ prompt = conv.get_prompt()
+
+ headers = {"User-Agent": "LLaVA Client"}
+ pload = {
+ "model": args.model_name,
+ "prompt": prompt,
+ "max_new_tokens": args.max_new_tokens,
+ "temperature": 0.7,
+ "stop": conv.sep,
+ }
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers,
+ json=pload, stream=True)
+
+ print(prompt.replace(conv.sep, "\n"), end="")
+ for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
+ if chunk:
+ data = json.loads(chunk.decode("utf-8"))
+ output = data["text"].split(conv.sep)[-1]
+ print(output, end="\r")
+ print("")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
+ parser.add_argument("--worker-address", type=str)
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
+ parser.add_argument("--max-new-tokens", type=int, default=32)
+ parser.add_argument("--message", type=str, default=
+ "Tell me a story with more than 1000 words.")
+ args = parser.parse_args()
+
+ main()
diff --git a/videollama2/train.py b/videollama2/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..99e07d9c51e2e64b7751a4e4136302e54a8473d4
--- /dev/null
+++ b/videollama2/train.py
@@ -0,0 +1,583 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
+# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
+# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import os
+import copy
+import json
+import random
+import pathlib
+import traceback
+from dataclasses import dataclass, field
+from typing import Dict, Optional, Sequence, List
+
+# torch-related packages
+# NOTE: torch must be imported before transformers. Otherwise, `Segmentation fault (core dumped)` will occur.
+import torch
+from torch.utils.data import Dataset
+
+import transformers
+from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock
+
+import sys
+sys.path.append('./')
+from videollama2.model import *
+from videollama2.constants import NUM_FRAMES, IGNORE_INDEX, MODAL_INDEX_MAP
+from videollama2.mm_utils import tokenizer_multimodal_token, process_video, process_image
+from videollama2.videollama2_trainer import (VideoLLaMA2Trainer,
+ get_peft_state_maybe_zero_3, get_peft_state_non_lora_maybe_zero_3,
+ find_all_linear_names, safe_save_model_for_hf_trainer
+)
+
+# NOTE: fast tokenizer warning issue: https://github.com/huggingface/transformers/issues/5486
+os.environ["TOKENIZERS_PARALLELISM"] = "true"
+
+local_rank = None
+
+
+def rank0_print(*args):
+ if local_rank == 0:
+ print(*args)
+
+
+def set_seed(seed=42):
+ """
+ Set the random seed for reproducible results.
+
+ :param seed: An integer value to be used as the random seed.
+ """
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed) # for multi-GPU setups
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+
+
+@dataclass
+class ModelArguments:
+ # LLM Arguments
+ model_type: Optional[str] = field(default="videollama2", metadata={"help": "Model type selected in the list: " + ", ".join(VLLMs.keys())})
+ model_path: Optional[str] = field(default="lmsys/vicuna-7b-v1.5")
+ version: Optional[str] = field(default="v1", metadata={"help": "Version of the conversation template."})
+ freeze_backbone: bool = field(default=False, metadata={"help": "Whether to freeze the LLM backbone."})
+ # Connector Arguments
+ mm_projector_type: Optional[str] = field(default='linear')
+ tune_mm_mlp_adapter: bool = field(default=False)
+ pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
+ # Vision tower Arguments
+ vision_tower: Optional[str] = field(default=None)
+ mm_vision_select_layer: Optional[int] = field(default=-1)
+ mm_vision_select_feature: Optional[str] = field(default="patch")
+
+
+@dataclass
+class DataArguments:
+ # Path Arguments
+ data_path: str = field(default=None, metadata={"help": "Path to the training data."})
+ # image_folder: Optional[str] = field(default=None)
+ # video_folder: Optional[str] = field(default=None)
+ data_folder: Optional[str] = field(default=None)
+ # Loading Arguments
+ is_multimodal: bool = False
+ lazy_preprocess: bool = False
+ num_frames: Optional[int] = field(default=None)
+ # Preprocess Arguments
+ image_aspect_ratio: str = 'square'
+
+
+@dataclass
+class TrainingArguments(transformers.TrainingArguments):
+ optim: str = field(default="adamw_torch")
+ mm_projector_lr: Optional[float] = None
+ freeze_mm_mlp_adapter: bool = field(default=False)
+ remove_unused_columns: bool = field(default=False)
+ cache_dir: Optional[str] = field(default=None)
+ # Training Data Arguments
+ group_by_modality_length: bool = field(default=False)
+ model_max_length: int = field(
+ default=512,
+ metadata={
+ "help":
+ "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
+ },
+ )
+ # Lora or Quant Arguments
+ double_quant: bool = field(
+ default=True,
+ metadata={"help": "Compress the quantization statistics through double quantization."}
+ )
+ quant_type: str = field(
+ default="nf4",
+ metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
+ )
+ bits: int = field(
+ default=16,
+ metadata={"help": "How many bits to use."}
+ )
+ lora_enable: bool = False
+ lora_r: int = 64
+ lora_alpha: int = 16
+ lora_dropout: float = 0.05
+ lora_weight_path: str = ""
+ lora_bias: str = "none"
+
+
+def preprocess_plain(
+ sources: Sequence[str],
+ tokenizer: transformers.PreTrainedTokenizer,
+ modal_token: str = None,
+) -> Dict:
+ roles = {"human": "user", "gpt": "assistant"}
+ conversations = []
+ input_ids = []
+ targets = []
+ for source in sources:
+ # 1. apply chat template for input conversation
+ assert len(source) == 2
+ assert modal_token in source[0]['value']
+ message = [
+ {'role': 'user', 'content': modal_token},
+ {'role': 'assistant', 'content': source[1]['value']}
+ ]
+ conversation = " ".join([sentence['value'] for sentence in source])
+
+ input_id = tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt')
+ target = copy.deepcopy(input_id)
+ target[input_id == MODAL_INDEX_MAP[modal_token]] = IGNORE_INDEX
+
+ input_ids.append(input_id)
+ targets.append(target)
+
+ return dict(input_ids=input_ids, labels=targets)
+
+
+def preprocess(
+ sources: Sequence[str],
+ tokenizer: transformers.PreTrainedTokenizer,
+ modal_token: str = None,
+) -> Dict:
+ roles = {"human": "user", "gpt": "assistant"}
+
+ # Apply prompt templates
+ conversations = []
+ input_ids = []
+ targets = []
+ for i, source in enumerate(sources):
+ if roles[source[0]["from"]] != "user":
+ # Skip the first one if it is not from human
+ source = source[1:]
+
+ message = [{'role': roles[sentence['from']], 'content': sentence['value']} for sentence in source]
+ conversation = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=False)
+ input_ids.append(tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt'))
+ targets.append(copy.deepcopy(input_ids[-1]))
+
+ assert len(source) % 2 == 0, f"Invalid conversation length {len(source)}."
+
+ cur = 0
+ message = []
+ for idx, sentence in enumerate(source):
+ if idx % 2 == 1:
+ tmp_message = [
+ {'role': roles[source[idx-1]['from']], 'content': source[idx-1]['value']},
+ {'role': roles[sentence['from']], 'content': sentence['value']}
+ ]
+
+ instruction = tokenizer.apply_chat_template(message + tmp_message[:1], tokenize=False, add_generation_prompt=True)
+ conversation = tokenizer.apply_chat_template(message + tmp_message, tokenize=False, add_generation_prompt=False)
+
+ instruction_len = len(tokenizer_multimodal_token(instruction, tokenizer, modal_token, return_tensors='pt'))
+ conversation_len = len(tokenizer_multimodal_token(conversation, tokenizer, modal_token, return_tensors='pt'))
+
+ targets[-1][cur:instruction_len] = IGNORE_INDEX
+
+ # print("instruction: ----------------")
+ # print(instruction)
+ # print("conversation: ----------------")
+ # print(conversation)
+ # print("training targets: ----------------")
+ # print(tokenizer.decode(targets[-1][instruction_len:conversation_len]))
+ # print(input_ids[-1][cur:conversation_len])
+ # print(targets[-1][cur:conversation_len])
+ # print(targets[-1][instruction_len:conversation_len])
+
+ cur = conversation_len
+ message += tmp_message
+
+ return dict(input_ids=input_ids, labels=targets)
+
+
+def preprocess_multimodal(
+ sources: Sequence[str],
+ data_args: DataArguments,
+ modal_token: str = None,
+) -> Dict:
+ is_multimodal = data_args.is_multimodal
+ if not is_multimodal:
+ return sources
+
+ assert modal_token in MODAL_INDEX_MAP, f"Unsupported modal token {modal_token}."
+
+ for source in sources:
+ for sentence in source:
+ if modal_token in sentence['value']:
+ sentence['value'] = sentence['value'].replace(modal_token, '').strip()
+ sentence['value'] = modal_token + '\n' + sentence['value']
+ sentence['value'] = sentence['value'].strip()
+ replace_token = modal_token
+ # TODO: fix this for multimedia, e.g., , , etc.
+ sentence["value"] = sentence["value"].replace(modal_token, replace_token)
+
+ return sources
+
+
+class LazySupervisedDataset(Dataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(self, data_path: str,
+ tokenizer: transformers.PreTrainedTokenizer,
+ data_args: DataArguments):
+ super(LazySupervisedDataset, self).__init__()
+ list_data_dict = json.load(open(data_path, "r"))
+
+ rank0_print("Formatting inputs...Skip in lazy mode")
+ self.tokenizer = tokenizer
+ self.list_data_dict = list_data_dict
+ self.data_args = data_args
+
+ def __len__(self):
+ return len(self.list_data_dict)
+
+ @property
+ def lengths(self):
+ length_list = []
+ for sample in self.list_data_dict:
+ img_tokens = 576 if 'image' in sample else 0
+ length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
+ return length_list
+
+ @property
+ def modality_lengths(self):
+ length_list = []
+ for sample in self.list_data_dict:
+ cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
+ cur_len = cur_len if 'image' in sample else -cur_len
+ length_list.append(cur_len)
+ return length_list
+
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
+ sources = self.list_data_dict[i]
+ if isinstance(i, int):
+ sources = [sources]
+ assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
+
+ image_processor = self.data_args.image_processor
+ video_processor = self.data_args.video_processor
+
+ num_frames = NUM_FRAMES if self.data_args.num_frames is None else self.data_args.num_frames
+
+ if 'image' in sources[0]:
+ image_file = self.list_data_dict[i]['image']
+ image_folder = self.data_args.data_folder
+ image_file = os.path.join(image_folder, image_file)
+
+ try:
+ image = process_image(image_file, image_processor, aspect_ratio=self.data_args.image_aspect_ratio)
+ except:
+ traceback.print_exc()
+ backup_idx = random.randint(0, len(self.list_data_dict) - 1)
+ print(f"Encounted error when reading image {image_file}, use {backup_idx}-th example instead!!!")
+ return self.__getitem__(backup_idx)
+
+ # place tag to question head.
+ modal_token = ""
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, modal_token)
+ elif 'video' in sources[0]:
+ video_file = self.list_data_dict[i]['video']
+ video_folder = self.data_args.data_folder
+ video_file = os.path.join(video_folder, video_file)
+
+ try:
+ video = process_video(video_file, video_processor, aspect_ratio=self.data_args.image_aspect_ratio, num_frames=num_frames)
+ except Exception as e:
+ traceback.print_exc()
+ backup_idx = random.randint(0, len(self.list_data_dict) - 1)
+ print(f"Encounted error when reading video {video_file}, use {backup_idx}-th example instead!!!")
+ return self.__getitem__(backup_idx)
+
+ # place tag to question head.
+ modal_token = ""
+ sources = preprocess_multimodal(copy.deepcopy([e["conversations"] for e in sources]), self.data_args, modal_token)
+ else:
+ modal_token = None
+ sources = copy.deepcopy([e["conversations"] for e in sources])
+
+ if self.data_args.is_pretraining:
+ data_dict = preprocess_plain(sources, self.tokenizer, modal_token=modal_token)
+ else:
+ data_dict = preprocess(sources, self.tokenizer, modal_token=modal_token)
+
+ if isinstance(i, int):
+ data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0])
+
+ # image exist in the data
+ if 'image' in self.list_data_dict[i]:
+ data_dict['image'] = image
+ elif 'video' in self.list_data_dict[i]:
+ data_dict['video'] = video
+ elif self.data_args.is_multimodal:
+ # image does not exist in the data, but the model is multimodal
+ data_dict['image'] = torch.zeros(3, self.data_args.image_size, self.data_args.image_size)
+ return data_dict
+
+
+@dataclass
+class DataCollatorForSupervisedDataset(object):
+ """Collate examples for supervised fine-tuning."""
+
+ tokenizer: transformers.PreTrainedTokenizer
+
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
+ input_ids, labels = tuple([instance[key] for instance in instances]
+ for key in ("input_ids", "labels"))
+ input_ids = torch.nn.utils.rnn.pad_sequence(
+ input_ids,
+ batch_first=True,
+ padding_value=self.tokenizer.pad_token_id)
+ labels = torch.nn.utils.rnn.pad_sequence(labels,
+ batch_first=True,
+ padding_value=IGNORE_INDEX)
+ input_ids = input_ids[:, :self.tokenizer.model_max_length]
+ labels = labels[:, :self.tokenizer.model_max_length]
+ batch = dict(
+ input_ids=input_ids,
+ labels=labels,
+ attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
+ )
+
+ # work for 'images' argument in `prepare_inputs_labels_for_multimodal` of LlavaMetaForCausalLM in llava_arch.py
+ batch['images'] = []
+ for instance in instances:
+ for modal_token in MODAL_INDEX_MAP.keys():
+ modal_token = modal_token.lower()
+ # MODAL_TOKEN shape like: , , ...
+ modal_name = re.findall(f'[<](.*)[>]', modal_token)
+ assert len(modal_name) == 1
+ modal_name = modal_name[0]
+ if modal_name in instance:
+ batch['images'].append((instance[modal_name], modal_name))
+
+ return batch
+
+
+def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
+ data_args) -> Dict:
+ """Make dataset and collator for supervised fine-tuning."""
+ train_dataset = LazySupervisedDataset(
+ tokenizer=tokenizer,
+ data_path=data_args.data_path,
+ data_args=data_args
+ )
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
+ return dict(train_dataset=train_dataset,
+ eval_dataset=None,
+ data_collator=data_collator)
+
+
+def train(attn_implementation=None):
+ global local_rank
+ set_seed(42)
+
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+
+ local_rank = training_args.local_rank
+ compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
+
+ bnb_model_from_pretrained_args = {}
+ if training_args.bits in [4, 8]:
+ from transformers import BitsAndBytesConfig
+ bnb_model_from_pretrained_args.update(dict(
+ # device_map={"": training_args.device},
+ # BUG: High version transformers report error:
+ # ValueError: You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing `quantization_config` argument at the same time
+ # load_in_4bit=training_args.bits == 4,
+ # load_in_8bit=training_args.bits == 8,
+ quantization_config=BitsAndBytesConfig(
+ load_in_4bit=training_args.bits == 4,
+ load_in_8bit=training_args.bits == 8,
+ llm_int8_skip_modules=["mm_projector"],
+ llm_int8_threshold=6.0,
+ llm_int8_has_fp16_weight=False,
+ bnb_4bit_compute_dtype=compute_dtype,
+ bnb_4bit_use_double_quant=training_args.double_quant,
+ bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
+ bnb_4bit_quant_storage=compute_dtype,
+ )
+ ))
+
+ config = VLLMConfigs[model_args.model_type].from_pretrained(model_args.model_path, trust_remote_code=True)
+ config._attn_implementation = attn_implementation
+
+ if model_args.vision_tower is not None:
+ model = VLLMs[model_args.model_type].from_pretrained(
+ model_args.model_path,
+ config=config,
+ cache_dir=training_args.cache_dir,
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
+ do_sample=True,
+ **bnb_model_from_pretrained_args
+ )
+ if 'mixtral' in model_args.model_type:
+ import deepspeed
+ deepspeed.utils.set_z3_leaf_modules(model, [MixtralSparseMoeBlock])
+ else:
+ model = transformers.LlamaForCausalLM.from_pretrained(
+ model_args.model_path,
+ config=config,
+ cache_dir=training_args.cache_dir,
+ torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
+ do_sample=True,
+ **bnb_model_from_pretrained_args
+ )
+ model.config.use_cache = False
+
+ if model_args.freeze_backbone:
+ model.model.requires_grad_(False)
+
+ if training_args.bits in [4, 8]:
+ from peft import prepare_model_for_kbit_training
+ model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
+
+ if training_args.gradient_checkpointing:
+ if hasattr(model, "enable_input_require_grads"):
+ model.enable_input_require_grads()
+ else:
+ def make_inputs_require_grad(module, input, output):
+ output.requires_grad_(True)
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
+
+ if training_args.lora_enable:
+ from peft import LoraConfig, get_peft_model
+ lora_config = LoraConfig(
+ r=training_args.lora_r,
+ lora_alpha=training_args.lora_alpha,
+ target_modules=find_all_linear_names(model),
+ lora_dropout=training_args.lora_dropout,
+ bias=training_args.lora_bias,
+ task_type="CAUSAL_LM",
+ )
+ if training_args.bits == 16:
+ if training_args.bf16:
+ model.to(torch.bfloat16)
+ if training_args.fp16:
+ model.to(torch.float16)
+ rank0_print("Adding LoRA adapters...")
+ model = get_peft_model(model, lora_config)
+
+
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
+ model_args.model_path,
+ cache_dir=training_args.cache_dir,
+ model_max_length=training_args.model_max_length,
+ padding_side="right",
+ use_fast=True,
+ )
+
+ if tokenizer.pad_token is None:
+ tokenizer.pad_token = tokenizer.unk_token
+
+ if model_args.vision_tower is not None:
+ # initialize vision encoder + multi-modal projector
+ model.get_model().initialize_vision_modules(model_args=model_args, fsdp=training_args.fsdp)
+
+ vision_tower = model.get_vision_tower()
+ vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
+
+ data_args.image_size = vision_tower.image_size
+
+ data_args.image_processor = vision_tower.image_processor
+ data_args.video_processor = vision_tower.video_processor if hasattr(vision_tower, "video_processor") else vision_tower.image_processor
+
+ data_args.is_multimodal = True
+
+ model.config.image_aspect_ratio = data_args.image_aspect_ratio
+ model.config.tokenizer_padding_side = tokenizer.padding_side
+ model.config.tokenizer_model_max_length = tokenizer.model_max_length
+
+ model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
+ if model_args.tune_mm_mlp_adapter:
+ model.requires_grad_(False)
+ for p in model.get_model().mm_projector.parameters():
+ p.requires_grad = True
+
+ if model_args.tune_mm_mlp_adapter:
+ data_args.is_pretraining = True
+ else:
+ data_args.is_pretraining = False
+
+ model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
+ if training_args.freeze_mm_mlp_adapter:
+ for p in model.get_model().mm_projector.parameters():
+ p.requires_grad = False
+
+ if training_args.bits in [4, 8]:
+ model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
+
+ model.config.mm_projector_lr = training_args.mm_projector_lr
+ model.config.num_frames = NUM_FRAMES if data_args.num_frames is None else data_args.num_frames
+
+ if training_args.bits in [4, 8]:
+ from peft.tuners.lora import LoraLayer
+ for name, module in model.named_modules():
+ if isinstance(module, LoraLayer):
+ if training_args.bf16:
+ module = module.to(torch.bfloat16)
+ if 'norm' in name:
+ module = module.to(torch.float32)
+ if 'lm_head' in name or 'embed_tokens' in name:
+ if hasattr(module, 'weight'):
+ if training_args.bf16 and module.weight.dtype == torch.float32:
+ module = module.to(torch.bfloat16)
+
+ print("Current model:", model)
+ data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
+ # select a Trainer
+ trainer = VideoLLaMA2Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
+
+ if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
+ trainer.train(resume_from_checkpoint=True)
+ else:
+ trainer.train()
+ trainer.save_state()
+
+ model.config.use_cache = True
+
+ if training_args.lora_enable:
+ state_dict = get_peft_state_maybe_zero_3(model.named_parameters(), training_args.lora_bias)
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(model.named_parameters())
+ if training_args.local_rank == 0 or training_args.local_rank == -1:
+ model.config.save_pretrained(training_args.output_dir)
+ model.save_pretrained(training_args.output_dir, state_dict=state_dict)
+ torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
+ else:
+ safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
+
+
+if __name__ == "__main__":
+ train()
diff --git a/videollama2/train_flash_attn.py b/videollama2/train_flash_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..14941d7197ff1be476b9f7db49f55a5bc87758db
--- /dev/null
+++ b/videollama2/train_flash_attn.py
@@ -0,0 +1,12 @@
+# Adopted from https://github.com/haotian-liu/LLaVA. Below is the original copyright:
+# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
+# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
+# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn.
+
+import sys
+sys.path.append('./')
+
+from videollama2.train import train
+
+if __name__ == "__main__":
+ train(attn_implementation="flash_attention_2")
diff --git a/videollama2/utils.py b/videollama2/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9f161afab1cf556197a578ef2e90ef973b7574d
--- /dev/null
+++ b/videollama2/utils.py
@@ -0,0 +1,126 @@
+import datetime
+import logging
+import logging.handlers
+import os
+import sys
+
+import requests
+
+from .constants import LOGDIR
+
+server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
+moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
+
+handler = None
+
+
+def build_logger(logger_name, logger_filename):
+ global handler
+
+ formatter = logging.Formatter(
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+
+ # Set the format of root handlers
+ if not logging.getLogger().handlers:
+ logging.basicConfig(level=logging.INFO)
+ logging.getLogger().handlers[0].setFormatter(formatter)
+
+ # Redirect stdout and stderr to loggers
+ stdout_logger = logging.getLogger("stdout")
+ stdout_logger.setLevel(logging.INFO)
+ sl = StreamToLogger(stdout_logger, logging.INFO)
+ sys.stdout = sl
+
+ stderr_logger = logging.getLogger("stderr")
+ stderr_logger.setLevel(logging.ERROR)
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
+ sys.stderr = sl
+
+ # Get logger
+ logger = logging.getLogger(logger_name)
+ logger.setLevel(logging.INFO)
+
+ # Add a file handler for all loggers
+ if handler is None:
+ os.makedirs(LOGDIR, exist_ok=True)
+ filename = os.path.join(LOGDIR, logger_filename)
+ handler = logging.handlers.TimedRotatingFileHandler(
+ filename, when='D', utc=True, encoding='UTF-8')
+ handler.setFormatter(formatter)
+
+ for name, item in logging.root.manager.loggerDict.items():
+ if isinstance(item, logging.Logger):
+ item.addHandler(handler)
+
+ return logger
+
+
+class StreamToLogger(object):
+ """
+ Fake file-like stream object that redirects writes to a logger instance.
+ """
+ def __init__(self, logger, log_level=logging.INFO):
+ self.terminal = sys.stdout
+ self.logger = logger
+ self.log_level = log_level
+ self.linebuf = ''
+
+ def __getattr__(self, attr):
+ return getattr(self.terminal, attr)
+
+ def write(self, buf):
+ temp_linebuf = self.linebuf + buf
+ self.linebuf = ''
+ for line in temp_linebuf.splitlines(True):
+ # From the io.TextIOWrapper docs:
+ # On output, if newline is None, any '\n' characters written
+ # are translated to the system default line separator.
+ # By default sys.stdout.write() expects '\n' newlines and then
+ # translates them so this is still cross platform.
+ if line[-1] == '\n':
+ self.logger.log(self.log_level, line.rstrip())
+ else:
+ self.linebuf += line
+
+ def flush(self):
+ if self.linebuf != '':
+ self.logger.log(self.log_level, self.linebuf.rstrip())
+ self.linebuf = ''
+
+
+def disable_torch_init():
+ """
+ Disable the redundant torch default initialization to accelerate model creation.
+ """
+ import torch
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
+
+
+def violates_moderation(text):
+ """
+ Check whether the text violates OpenAI moderation API.
+ """
+ url = "https://api.openai.com/v1/moderations"
+ headers = {"Content-Type": "application/json",
+ "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}
+ text = text.replace("\n", "")
+ data = "{" + '"input": ' + f'"{text}"' + "}"
+ data = data.encode("utf-8")
+ try:
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
+ flagged = ret.json()["results"][0]["flagged"]
+ except requests.exceptions.RequestException as e:
+ flagged = False
+ except KeyError as e:
+ flagged = False
+
+ return flagged
+
+
+def pretty_print_semaphore(semaphore):
+ if semaphore is None:
+ return "None"
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
diff --git a/videollama2/videollama2_trainer.py b/videollama2/videollama2_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e129352c4c2b3f7fb938fcc890da8939e3b73eb
--- /dev/null
+++ b/videollama2/videollama2_trainer.py
@@ -0,0 +1,369 @@
+# Adopted from: https://github.com/haotian-liu/LLaVA/blob/main/llava/train/llava_trainer.py
+import os
+import logging
+from typing import List, Optional
+
+import torch
+import torch.nn as nn
+from torch.utils.data import Sampler
+
+from transformers import Trainer
+from transformers.trainer import (
+ is_sagemaker_mp_enabled,
+ get_parameter_names,
+ has_length,
+ ALL_LAYERNORM_LAYERS,
+ logger,
+ TRAINER_STATE_NAME,
+)
+
+
+def maybe_zero_3(param, ignore_status=False, name=None):
+ from deepspeed import zero
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
+ if hasattr(param, "ds_id"):
+ if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
+ if not ignore_status:
+ logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
+ with zero.GatheredParameters([param]):
+ param = param.data.detach().cpu().clone()
+ else:
+ param = param.detach().cpu().clone()
+ return param
+
+
+def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
+ to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
+ to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
+ return to_return
+
+
+# Borrowed from peft.utils.get_peft_model_state_dict
+def get_peft_state_maybe_zero_3(named_params, bias):
+ if bias == "none":
+ to_return = {k: t for k, t in named_params if "lora_" in k}
+ elif bias == "all":
+ to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
+ elif bias == "lora_only":
+ to_return = {}
+ maybe_lora_bias = {}
+ lora_bias_names = set()
+ for k, t in named_params:
+ if "lora_" in k:
+ to_return[k] = t
+ bias_name = k.split("lora_")[0] + "bias"
+ lora_bias_names.add(bias_name)
+ elif "bias" in k:
+ maybe_lora_bias[k] = t
+ for k, t in maybe_lora_bias:
+ if bias_name in lora_bias_names:
+ to_return[bias_name] = t
+ else:
+ raise NotImplementedError
+ to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
+ return to_return
+
+
+def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
+ to_return = {k: t for k, t in named_params if "lora_" not in k}
+ if require_grad_only:
+ to_return = {k: t for k, t in to_return.items() if t.requires_grad}
+ to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
+ return to_return
+
+
+def find_all_linear_names(model):
+ cls = torch.nn.Linear
+ lora_module_names = set()
+ multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
+ for name, module in model.named_modules():
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
+ continue
+ if isinstance(module, cls):
+ names = name.split('.')
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
+
+ if 'lm_head' in lora_module_names: # needed for 16-bit
+ lora_module_names.remove('lm_head')
+ return list(lora_module_names)
+
+
+def safe_save_model_for_hf_trainer(trainer: Trainer,
+ output_dir: str):
+ """Collects the state dict and dump to disk."""
+
+ if getattr(trainer.args, "tune_mm_mlp_adapter", False):
+ # Only save Adapter
+ keys_to_match = ['mm_projector']
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
+ trainer.model.config.save_pretrained(output_dir)
+
+ current_folder = output_dir.split('/')[-1]
+ parent_folder = os.path.dirname(output_dir)
+ if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
+ if current_folder.startswith('checkpoint-'):
+ mm_projector_folder = os.path.join(parent_folder, "mm_projector")
+ os.makedirs(mm_projector_folder, exist_ok=True)
+ torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
+ else:
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
+ return
+
+ if trainer.deepspeed:
+ torch.cuda.synchronize()
+ trainer.save_model(output_dir)
+ return
+
+ state_dict = trainer.model.state_dict()
+ if trainer.args.should_save:
+ cpu_state_dict = {
+ key: value.cpu()
+ for key, value in state_dict.items()
+ }
+ del state_dict
+ trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
+
+
+def split_to_even_chunks(indices, lengths, num_chunks):
+ """
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
+ """
+
+ if len(indices) % num_chunks != 0:
+ return [indices[i::num_chunks] for i in range(num_chunks)]
+
+ num_indices_per_chunk = len(indices) // num_chunks
+
+ chunks = [[] for _ in range(num_chunks)]
+ chunks_lengths = [0 for _ in range(num_chunks)]
+ for index in indices:
+ shortest_chunk = chunks_lengths.index(min(chunks_lengths))
+ chunks[shortest_chunk].append(index)
+ chunks_lengths[shortest_chunk] += lengths[index]
+ if len(chunks[shortest_chunk]) == num_indices_per_chunk:
+ chunks_lengths[shortest_chunk] = float("inf")
+
+ return chunks
+
+
+def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
+ assert all(l != 0 for l in lengths), "Should not have zero length."
+ if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
+ # all samples are in the same modality
+ return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator)
+ mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
+ lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
+
+ mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
+ lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
+ megabatch_size = world_size * batch_size
+ mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
+ lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
+
+ last_mm = mm_megabatches[-1]
+ last_lang = lang_megabatches[-1]
+ additional_batch = last_mm + last_lang
+ megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
+ megabatch_indices = torch.randperm(len(megabatches), generator=generator)
+ megabatches = [megabatches[i] for i in megabatch_indices]
+
+ if len(additional_batch) > 0:
+ megabatches.append(sorted(additional_batch))
+
+ return [i for megabatch in megabatches for i in megabatch]
+
+
+def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
+ # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
+ indices = torch.randperm(len(lengths), generator=generator)
+ megabatch_size = world_size * batch_size
+ megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
+ megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
+ megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
+
+ return [i for megabatch in megabatches for batch in megabatch for i in batch]
+
+
+class LengthGroupedSampler(Sampler):
+ r"""
+ Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
+ keeping a bit of randomness.
+ """
+
+ def __init__(
+ self,
+ batch_size: int,
+ world_size: int,
+ lengths: Optional[List[int]] = None,
+ generator=None,
+ group_by_modality: bool = False,
+ ):
+ if lengths is None:
+ raise ValueError("Lengths must be provided.")
+
+ self.batch_size = batch_size
+ self.world_size = world_size
+ self.lengths = lengths
+ self.generator = generator
+ self.group_by_modality = group_by_modality
+
+ def __len__(self):
+ return len(self.lengths)
+
+ def __iter__(self):
+ if self.group_by_modality:
+ indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
+ else:
+ indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
+ return iter(indices)
+
+
+class VideoLLaMA2Trainer(Trainer):
+
+ def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
+ if self.train_dataset is None or not has_length(self.train_dataset):
+ return None
+
+ if self.args.group_by_modality_length:
+ lengths = self.train_dataset.modality_lengths
+ return LengthGroupedSampler(
+ self.args.train_batch_size,
+ world_size=self.args.world_size * self.args.gradient_accumulation_steps,
+ lengths=lengths,
+ group_by_modality=True,
+ )
+ else:
+ return super()._get_train_sampler()
+
+ def create_optimizer(self):
+ """
+ Setup the optimizer.
+
+ We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
+ Trainer's init through `optimizers`, or subclass and override this method in a subclass.
+ """
+ if is_sagemaker_mp_enabled():
+ return super().create_optimizer()
+
+ opt_model = self.model
+
+ if self.optimizer is None:
+ decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
+ if self.args.mm_projector_lr is not None:
+ projector_parameters = [name for name, _ in opt_model.named_parameters() if "mm_projector" in name]
+ optimizer_grouped_parameters = [
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ "lr": self.args.mm_projector_lr,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in projector_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ "lr": self.args.mm_projector_lr,
+ },
+ ]
+ else:
+ optimizer_grouped_parameters = [
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)
+ ],
+ "weight_decay": self.args.weight_decay,
+ },
+ {
+ "params": [
+ p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)
+ ],
+ "weight_decay": 0.0,
+ },
+ ]
+
+ optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args)
+
+ self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
+ if optimizer_cls.__name__ == "Adam8bit":
+ import bitsandbytes
+
+ manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
+
+ skipped = 0
+ for module in opt_model.modules():
+ if isinstance(module, nn.Embedding):
+ skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values())
+ logger.info(f"skipped {module}: {skipped/2**20}M params")
+ manager.register_module_override(module, "weight", {"optim_bits": 32})
+ logger.debug(f"bitsandbytes: will optimize {module} in fp32")
+ logger.info(f"skipped: {skipped/2**20}M params")
+
+ return self.optimizer
+
+ def _save_checkpoint(self, model, trial, metrics=None):
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
+
+ run_dir = self._get_output_dir(trial=trial)
+ output_dir = os.path.join(run_dir, checkpoint_folder)
+
+ # Only save Adapter
+ keys_to_match = ['mm_projector', 'vision_resampler']
+
+ weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
+
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
+ self.model.config.save_pretrained(output_dir)
+ torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
+ # Save optimizer and scheduler
+ self._save_optimizer_and_scheduler(output_dir)
+ # Save RNG state
+ self._save_rng_state(output_dir)
+ self.state.save_to_json(os.path.join(output_dir, TRAINER_STATE_NAME))
+ self.args.distributed_state.wait_for_everyone()
+ else:
+ # NOTE: Supporting save complete lora checkpoint during training.
+ if self.args.lora_enable:
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
+
+ run_dir = self._get_output_dir(trial=trial)
+ output_dir = os.path.join(run_dir, checkpoint_folder)
+
+ state_dict = get_peft_state_maybe_zero_3(self.model.named_parameters(), self.args.lora_bias)
+ non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(self.model.named_parameters())
+ if self.args.local_rank == 0 or self.args.local_rank == -1:
+ # save for acquring `config.json`
+ self.model.config.save_pretrained(output_dir)
+ # save for acquring `adapter_config.json`, `adapter_model.bin`
+ # self.model.save_pretrained(output_dir, state_dict=state_dict)
+ torch.save(non_lora_state_dict, os.path.join(output_dir, 'non_lora_trainables.bin'))
+
+ # save for acquring lora adapter parameters & trainer states: `adapter_config.json`, `adapter_model.safetensors`
+ super(VideoLLaMA2Trainer, self)._save_checkpoint(model, trial, metrics)
+ else:
+ super(VideoLLaMA2Trainer, self)._save_checkpoint(model, trial, metrics)
+
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
+ if getattr(self.args, 'tune_mm_mlp_adapter', False):
+ pass
+ else:
+ super(VideoLLaMA2Trainer, self)._save(output_dir, state_dict)