diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..22332ee0345cca6a6dbd0ebfc8935d5c2c8086c7 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,13 @@ 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
+VideoLLaMA2/assets/cat_and_chicken.mp4 filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/assets/logo.png filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/assets/pipeline.png filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/assets/sora.mp4 filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/assets/sora.png filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/videollama2/serve/examples/1034346401.mp4 filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/videollama2/serve/examples/desert.jpg filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/videollama2/serve/examples/sample_demo_1.mp4 filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/videollama2/serve/examples/sample_demo_3.mp4 filter=lfs diff=lfs merge=lfs -text
+VideoLLaMA2/videollama2/serve/examples/sample_demo_9.mp4 filter=lfs diff=lfs merge=lfs -text
diff --git a/VideoLLaMA2/.gitignore b/VideoLLaMA2/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..2a047f8b2e53bee34ec876220944293c3de82bd8
--- /dev/null
+++ b/VideoLLaMA2/.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/VideoLLaMA2/LICENSE b/VideoLLaMA2/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8
--- /dev/null
+++ b/VideoLLaMA2/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/VideoLLaMA2/README.md b/VideoLLaMA2/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..dbe092f497720f7030d8da81e3c137c419a316b5
--- /dev/null
+++ b/VideoLLaMA2/README.md
@@ -0,0 +1,372 @@
+
+
+
+
+
+ If our project helps you, please give us a star ⭐ on GitHub to support us. 🙏🙏
+
+
+
+[](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2-AV)
+[](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2)
+[](https://huggingface.co/collections/DAMO-NLP-SG/videollama-2-6669b6b6f0493188305c87ed)
+[](https://huggingface.co/datasets/DAMO-NLP-SG/Multi-Source-Video-Captioning)
+[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/blob/main/LICENSE)
+[](https://hits.seeyoufarm.com)
+[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aopen+is%3Aissue)
+[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aissue+is%3Aclosed)
+[](https://huggingface.co/papers/2406.07476)
+[](https://arxiv.org/abs/2406.07476)
+
+
+
+[](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-egoschema-1?p=videollama-2-advancing-spatial-temporal)
+[](https://paperswithcode.com/sota/video-question-answering-on-perception-test?p=videollama-2-advancing-spatial-temporal)
+[](https://paperswithcode.com/sota/video-question-answering-on-mvbench?p=videollama-2-advancing-spatial-temporal)
+[](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-video-mme-1?p=videollama-2-advancing-spatial-temporal)
+[](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 ✨.
+
+
+> [**VideoLLaMA 3: Frontier Multimodal Foundation Models for Image and Video Understanding**](https://github.com/DAMO-NLP-SG/VideoLLaMA3)
+> Boqiang Zhang* , Kehan Li* , Zesen Cheng* , Zhiqiang Hu* , Yuqian Yuan* , Guanzheng Chen* , Sicong Leng* , Yuming Jiang* , Hang Zhang* , Xin Li* , Peng Jin, Wenqi Zhang, Fan Wang, Lidong Bing, Deli Zhao
+[](https://github.com/DAMO-NLP-SG/VideoLLaMA3) [](https://github.com/DAMO-NLP-SG/VideoLLaMA3) [](https://arxiv.org/abs/2501.13106)
+
+> [**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
+[](https://github.com/DAMO-NLP-SG/Video-LLaMA) [](https://github.com/DAMO-NLP-SG/Video-LLaMA) [](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
+[](https://github.com/DAMO-NLP-SG/VCD) [](https://github.com/DAMO-NLP-SG/VCD) [](https://arxiv.org/abs/2311.16922)
+
+> [**The Curse of Multi-Modalities: Evaluating Hallucinations of Large Multimodal Models across Language, Visual, and Audio**](https://arxiv.org/abs/2410.12787)
+> Sicong Leng, Yun Xing, Zesen Cheng, Yang Zhou, Hang Zhang, Xin Li, Deli Zhao, Shijian Lu, Chunyan Miao, Lidong Bing
+[](https://github.com/DAMO-NLP-SG/CMM) [](https://github.com/DAMO-NLP-SG/CMM) [](https://arxiv.org/abs/2410.12787)
+
+> [**Breaking the Memory Barrier: Near Infinite Batch Size Scaling for Contrastive Loss**](https://arxiv.org/abs/2410.17243)
+> Zesen Cheng*, Hang Zhang*, Kehan Li*, Sicong Leng, Zhiqiang Hu, Fei Wu, Deli Zhao, Xin Li, Lidong Bing
+[](https://github.com/DAMO-NLP-SG/Inf-CLIP) [](https://github.com/DAMO-NLP-SG/Inf-CLIP) [](https://arxiv.org/abs/2410.17243)
+
+
+
+
+
+
+## 📰 News
+* **[2025.01.21]** 🚀🚀 We are excited to officially launch [VideoLLaMA3](https://github.com/DAMO-NLP-SG/VideoLLaMA3), featuring enhanced performance across image and video benchmarks, along with a variety of easy-to-follow inference cookbooks. Try it out today!
+* **[2024.10.22]** Release checkpoints of [VideoLLaMA2.1-7B-AV](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-AV). The audio_visual branch code can be seen here: https://github.com/DAMO-NLP-SG/VideoLLaMA2/tree/audio_visual.
+* **[2024.10.15]** Release checkpoints of [VideoLLaMA2.1-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base) and [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F).
+* **[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
+
+
+### Audio QA
+
+
+### Audio-Visual QA
+
+
+
+## :earth_americas: Model Zoo
+### Vision-only Checkpoints
+| 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 |
+| [VideoLLaMA2.1-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base) | Base | [siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) | [Qwen2-7B-Instruct](https://huggingface.co/Qwen/Qwen2-7B-Instruct) | 16 |
+| [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F) | Chat | [siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) | [Qwen2-7B-Instruct](https://huggingface.co/Qwen/Qwen2-7B-Instruct) | 16 |
+
+
+### Audio-Visual Checkpoints
+| Model Name | Type | Audio Encoder | Language Decoder |
+|:-------------------|:----------------|:----------------|:------------------|
+| [VideoLLaMA2.1-7B-AV](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-AV) | Chat | [Fine-tuned BEATs_iter3+(AS2M)(cpt2)](https://1drv.ms/u/s!AqeByhGUtINrgcpj8ujXH1YUtxooEg?e=E9Ncea) | [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F) |
+
+
+
+## [🤗 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
+```
+
+### Multiple-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.1-7B-16F-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.1-7B-16F'
+ # Base model inference (only need to replace model_path)
+ # model_path = 'DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-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/), [**Qwen2**](https://huggingface.co/collections/Qwen/qwen2-6659360b33528ced941e557f), [**SigLIP**](https://huggingface.co/collections/google/siglip-659d5e62f0ae1a57ae0e83ba), [**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/).
+* [**Magpie**](https://github.com/magpie-align/magpie), [**ALLaVA**](https://github.com/FreedomIntelligence/ALLaVA), [**AVInstruct**](https://github.com/rikeilong/Bay-CAT/tree/main/AVinstruct).
+
+
+## 🔒 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/VideoLLaMA2/assets/cat_and_chicken.mp4 b/VideoLLaMA2/assets/cat_and_chicken.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..e5898c862833c17ffbce625736fc6614fb14fe7c
--- /dev/null
+++ b/VideoLLaMA2/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/VideoLLaMA2/assets/logo.png b/VideoLLaMA2/assets/logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..1b2c52bfb2a042fb0df0d62d68425ce61d4506b2
--- /dev/null
+++ b/VideoLLaMA2/assets/logo.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cd9a3a969f931fb23ed371de960ddc589136a937df901b2b08e2750fabf6dd8e
+size 503863
diff --git a/VideoLLaMA2/assets/pipeline.png b/VideoLLaMA2/assets/pipeline.png
new file mode 100644
index 0000000000000000000000000000000000000000..29f32809e0e7744a07de4b00602a67549673f333
--- /dev/null
+++ b/VideoLLaMA2/assets/pipeline.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:eeab6d9f13787337b40399427e419506f49b55a4fb4fe40ba91e25618d03eeb0
+size 4375052
diff --git a/VideoLLaMA2/assets/sora.mp4 b/VideoLLaMA2/assets/sora.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..61d726eac64b06fe969c9d4b105303b8c0eeb88e
--- /dev/null
+++ b/VideoLLaMA2/assets/sora.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:24e5f0ea3353f23225d00efcdf136fa6dc346301fc34082790e2152c80fa0490
+size 14978533
diff --git a/VideoLLaMA2/assets/sora.png b/VideoLLaMA2/assets/sora.png
new file mode 100644
index 0000000000000000000000000000000000000000..b1619da272d6caab2c128c62c4c05f3b143c43bb
--- /dev/null
+++ b/VideoLLaMA2/assets/sora.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6b69de5c87b429c7b1a87de6f9cb3f5ec6aec5f58ab6ab7c0f727a5d0ec259a5
+size 1051277
diff --git a/VideoLLaMA2/pyproject.toml b/VideoLLaMA2/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..0626368ff930639d4dfd8398517caba980bd1cc1
--- /dev/null
+++ b/VideoLLaMA2/pyproject.toml
@@ -0,0 +1,41 @@
+[build-system]
+requires = ["pdm-backend"]
+build-backend = "pdm.backend"
+
+[project]
+name = "videollama2"
+version = "1.0"
+authors = [
+ {name = "Zesen Cheng", email = "cyanlaser@stu.pku.edu.cn"},
+ {name = "Hang Zhang"},
+ {name = "Xin Li"},
+]
+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", "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.urls]
+"Homepage" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2"
+"Bug Tracker" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues"
+
+[tool.pdm.build]
+excludes = ["./.git"]
+package-dir = "."
+includes = ["./videollama2"]
diff --git a/VideoLLaMA2/requirements.txt b/VideoLLaMA2/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..1ab867a975b65a7d3941cb654346a80f1f10e0c5
--- /dev/null
+++ b/VideoLLaMA2/requirements.txt
@@ -0,0 +1,39 @@
+--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
+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/VideoLLaMA2/scripts/custom/finetune.sh b/VideoLLaMA2/scripts/custom/finetune.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7ef00f420e23f1d11a124df95e88e14b79ae678a
--- /dev/null
+++ b/VideoLLaMA2/scripts/custom/finetune.sh
@@ -0,0 +1,73 @@
+#!/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=${3:-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=videollama2qwen2_downstream_sft
+RUN_NAME=siglip_tcv35_7b_16f
+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.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 DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-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 16 \
+ --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 \
+ --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/VideoLLaMA2/scripts/custom/finetune_lora.sh b/VideoLLaMA2/scripts/custom/finetune_lora.sh
new file mode 100644
index 0000000000000000000000000000000000000000..688fbe462d174228a7ac737038196db7ecb2734e
--- /dev/null
+++ b/VideoLLaMA2/scripts/custom/finetune_lora.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=${3:-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=videollama2qwen2_downstream_sft
+RUN_NAME=siglip_tcv35_7b_16f_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.py \
+ --lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
+ --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 DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-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 16 \
+ --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 \
+ --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/VideoLLaMA2/scripts/custom/finetune_qlora.sh b/VideoLLaMA2/scripts/custom/finetune_qlora.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a54eb75d2ee907ce2a6776f585d26a1a1e8a130a
--- /dev/null
+++ b/VideoLLaMA2/scripts/custom/finetune_qlora.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=${3:-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=videollama2qwen2_downstream_sft
+RUN_NAME=siglip_tcv35_7b_16f_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.py \
+ --lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 --bits 4 \
+ --deepspeed scripts/zero2.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 DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-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 16 \
+ --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 \
+ --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/VideoLLaMA2/scripts/eval/eval_video_cap_msvc.sh b/VideoLLaMA2/scripts/eval/eval_video_cap_msvc.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1bd08a8486175900069149ed2128472f07d52852
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_mcqa_egoschema.sh b/VideoLLaMA2/scripts/eval/eval_video_mcqa_egoschema.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ca19ce17531c47c8dfbadf8eac42e6599ce996d7
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_mcqa_mvbench.sh b/VideoLLaMA2/scripts/eval/eval_video_mcqa_mvbench.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ec549165cf5e1ee91ca6065e9d12b7a6b70048ba
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh b/VideoLLaMA2/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9649c79fd3e6091afa4bd4db90c14dc7a8e56a5f
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_mcqa_videomme.sh b/VideoLLaMA2/scripts/eval/eval_video_mcqa_videomme.sh
new file mode 100644
index 0000000000000000000000000000000000000000..650dec4a1f03d91648d8e1ca171b94dbc14872b3
--- /dev/null
+++ b/VideoLLaMA2/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.1-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/VideoLLaMA2/scripts/eval/eval_video_oqa_activitynet.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_activitynet.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5ab50c607cce2bbcc0f6b37cd0ae9fbaca43afde
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_msvd.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_msvd.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0c3ab3d50a12601825c0fd319c262f239c638006
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3cbc5d8b88cbb1daa6fecd0aa6ac5de40cc1a6a9
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2237eb519e25c8ebf7e829603d54e3ea9c6a513f
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_3_context.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_3_context.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a101367a1db0618586eceb1fda500d483bc5b08c
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8ed449ddc8541d17e45f6940d98dbb21fd4608bf
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh b/VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh
new file mode 100644
index 0000000000000000000000000000000000000000..263057867cb9e4116520709e6236ca1e488a32aa
--- /dev/null
+++ b/VideoLLaMA2/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.1-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}/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/VideoLLaMA2/scripts/vllava/finetune.sh b/VideoLLaMA2/scripts/vllava/finetune.sh
new file mode 100644
index 0000000000000000000000000000000000000000..68f11548d0bbbfd32fb158508451179a7a63c7e9
--- /dev/null
+++ b/VideoLLaMA2/scripts/vllava/finetune.sh
@@ -0,0 +1,73 @@
+#!/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=${3:-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=videollama2qwen2_vllava
+RUN_NAME=siglip_tcv35_7b_16f
+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.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 16 \
+ --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 \
+ --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/VideoLLaMA2/scripts/vllava/pretrain.sh b/VideoLLaMA2/scripts/vllava/pretrain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..37d2d64ef3f76341dcd379b0e1fd604542b62f39
--- /dev/null
+++ b/VideoLLaMA2/scripts/vllava/pretrain.sh
@@ -0,0 +1,73 @@
+#!/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=${3:-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=videollama2qwen2_vllava
+RUN_NAME=siglip_tcv35_7b_16f
+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.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 16 \
+ --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 \
+ --report_to tensorboard \
+ --run_name $RUN_NAME \
diff --git a/VideoLLaMA2/scripts/zero2.json b/VideoLLaMA2/scripts/zero2.json
new file mode 100644
index 0000000000000000000000000000000000000000..7a01fda5b48ae060042ea16d16c6e380f62371a0
--- /dev/null
+++ b/VideoLLaMA2/scripts/zero2.json
@@ -0,0 +1,23 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "train_micro_batch_size_per_gpu": "auto",
+ "train_batch_size": "auto",
+ "gradient_accumulation_steps": "auto",
+ "zero_optimization": {
+ "stage": 2,
+ "overlap_comm": true,
+ "contiguous_gradients": true,
+ "sub_group_size": 1e9,
+ "reduce_bucket_size": "auto"
+ }
+}
\ No newline at end of file
diff --git a/VideoLLaMA2/scripts/zero3.json b/VideoLLaMA2/scripts/zero3.json
new file mode 100644
index 0000000000000000000000000000000000000000..26e8f0db89be32d02f498891cfa6da3864c062f0
--- /dev/null
+++ b/VideoLLaMA2/scripts/zero3.json
@@ -0,0 +1,28 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "train_micro_batch_size_per_gpu": "auto",
+ "train_batch_size": "auto",
+ "gradient_accumulation_steps": "auto",
+ "zero_optimization": {
+ "stage": 3,
+ "overlap_comm": true,
+ "contiguous_gradients": true,
+ "sub_group_size": 1e9,
+ "reduce_bucket_size": "auto",
+ "stage3_prefetch_bucket_size": "auto",
+ "stage3_param_persistence_threshold": "auto",
+ "stage3_max_live_parameters": 1e9,
+ "stage3_max_reuse_distance": 1e9,
+ "stage3_gather_16bit_weights_on_model_save": true
+ }
+}
diff --git a/VideoLLaMA2/videollama2/__init__.py b/VideoLLaMA2/videollama2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..60e7f6f3ccfcf842a4911f4e55aee56090d34510
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/constants.py b/VideoLLaMA2/videollama2/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7fb3bd51eae9973c643efde183bac43c91976e8
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/conversation.py b/VideoLLaMA2/videollama2/conversation.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3be96e8e6cec839f289fcdd42db5d2ac24aacbd
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_cap_msvc_correctness.py b/VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_correctness.py
new file mode 100644
index 0000000000000000000000000000000000000000..0377e64abf2140f5211709fa1a0a7c79c1056e18
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_cap_msvc_detailedness.py b/VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_detailedness.py
new file mode 100644
index 0000000000000000000000000000000000000000..db580bc127ceb58c9a9d47ed5a76cb4d9f21e1d7
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_mcqa_mvbench.py b/VideoLLaMA2/videollama2/eval/eval_video_mcqa_mvbench.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd469000b5c97929a11580e90488377ccadb14dc
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_mcqa_videomme.py b/VideoLLaMA2/videollama2/eval/eval_video_mcqa_videomme.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e59bf0f8bb4c2286d7813f9bb054bd46a8ee41b
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_activitynet.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_activitynet.py
new file mode 100644
index 0000000000000000000000000000000000000000..48bfaa1482bc04275636bdbe7e64c7acb2451373
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py
new file mode 100644
index 0000000000000000000000000000000000000000..28426894aac7514e0ea77df022b92f55ebd27151
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py
new file mode 100644
index 0000000000000000000000000000000000000000..65c1976b52e5ad4417626c4c10a82d9b590071fc
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_vcgpt_3_context.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_3_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..9266a9d2ddef3c0c49fd3d872478b103738a2d11
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e7af115ba4561084987f6afb5ad0af35c2e5a25
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py b/VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cdea4291862bc00e79c6cf29e2abb13becf077c
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_cap_msvc.py b/VideoLLaMA2/videollama2/eval/inference_video_cap_msvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ffd64dc3c18256984bb9121ce4b1c4993e84dff
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_mcqa_egoschema.py b/VideoLLaMA2/videollama2/eval/inference_video_mcqa_egoschema.py
new file mode 100644
index 0000000000000000000000000000000000000000..482b8d7f5e94ef6f7fa4295e17c830a2675fe5ac
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_mcqa_mvbench.py b/VideoLLaMA2/videollama2/eval/inference_video_mcqa_mvbench.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6494d10fd2362df55ca154e2840f8bf0258ad2f
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py b/VideoLLaMA2/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..8823a8cdcc42fe3c2cd51c7994276450feb9f57b
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_mcqa_videomme.py b/VideoLLaMA2/videollama2/eval/inference_video_mcqa_videomme.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e960190844a50991a20c6ee1abdd56c8070cfa9
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_oqa_activitynet.py b/VideoLLaMA2/videollama2/eval/inference_video_oqa_activitynet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81fe094df1a9803fd9cfdce70a05ce03d13d963
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_oqa_vcgpt_consistency.py b/VideoLLaMA2/videollama2/eval/inference_video_oqa_vcgpt_consistency.py
new file mode 100644
index 0000000000000000000000000000000000000000..146bd8ecbeb46f7e9e0c9e208b6d5b4002411049
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/eval/inference_video_oqa_vcgpt_general.py b/VideoLLaMA2/videollama2/eval/inference_video_oqa_vcgpt_general.py
new file mode 100644
index 0000000000000000000000000000000000000000..332d7f1af8b9fe809947f7ea7e43e0a9c84bc87f
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/mm_utils.py b/VideoLLaMA2/videollama2/mm_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..434bc9a21dff968d2e03448e73955ff5a5d94aed
--- /dev/null
+++ b/VideoLLaMA2/videollama2/mm_utils.py
@@ -0,0 +1,345 @@
+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 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, num_threads=2)
+
+ 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]
+ else:
+ # NOTE: num_threads=1 is required to avoid deadlock in multiprocessing
+ # decord_vr = VideoReader(uri=video_path, ctx=cpu(0), num_threads=1)
+ decord_vr = VideoReader(video_path, ctx=cpu(0), num_threads=2)
+ 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/videollama2/model/__init__.py b/VideoLLaMA2/videollama2/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db31421c8ddf0888693d1e8a7dddd386156970bd
--- /dev/null
+++ b/VideoLLaMA2/videollama2/model/__init__.py
@@ -0,0 +1,193 @@
+# 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)
+ # Using the visual@MistralForCasualLM will cause the model to give random output when using finetuned qwen2 based varient
+ model = Videollama2Qwen2ForCausalLM.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()
+ # 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/videollama2/model/encoder.py b/VideoLLaMA2/videollama2/model/encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e9a83747404f5cd89bb1765401d3efd1d3d9a51
--- /dev/null
+++ b/VideoLLaMA2/videollama2/model/encoder.py
@@ -0,0 +1,164 @@
+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, load_pretrained=False):
+ super().__init__()
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
+
+ config = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
+ config._attn_implementation = "flash_attention_2"
+
+ if not load_pretrained:
+ self.vision_tower = CLIPVisionModel(config=config)
+ else:
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
+
+ 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.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, output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ return self.vision_tower.config
+
+ @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, load_pretrained=False):
+ super().__init__()
+
+ self.vision_tower_name = vision_tower
+ self.select_layer = args.mm_vision_select_layer
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
+
+ self.image_processor = SiglipImageProcessor.from_pretrained(self.vision_tower_name)
+
+ config = SiglipVisionConfig.from_pretrained(self.vision_tower_name)
+ config._attn_implementation = 'flash_attention_2'
+
+ if not load_pretrained:
+ self.vision_tower = SiglipVisionModel(config=config)
+ else:
+ self.vision_tower = SiglipVisionModel.from_pretrained(self.vision_tower_name)
+
+ 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.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, output_hidden_states=True)
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
+
+ return image_features
+
+ @property
+ def dtype(self):
+ return self.vision_tower.dtype
+
+ @property
+ def device(self):
+ return self.vision_tower.device
+
+ @property
+ def config(self):
+ return self.vision_tower.config
+
+ @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/videollama2/model/projector.py b/VideoLLaMA2/videollama2/model/projector.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5841e5436e553b11476e90d0bdd8d7c477f91ce
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/model/videollama2_arch.py b/VideoLLaMA2/videollama2/model/videollama2_arch.py
new file mode 100644
index 0000000000000000000000000000000000000000..22abe1942ffb7a678e355db435aa4db1d7ddb6e9
--- /dev/null
+++ b/VideoLLaMA2/videollama2/model/videollama2_arch.py
@@ -0,0 +1,263 @@
+# 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)
+ 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, load_pretrained=True)
+
+ 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
+
+ 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/videollama2/model/videollama2_llama.py b/VideoLLaMA2/videollama2/model/videollama2_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..887fb5fd643df3cbaa22a1c078c9934a2d183c61
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/model/videollama2_mistral.py b/VideoLLaMA2/videollama2/model/videollama2_mistral.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f8614e770c653b3ed943c6f2d023a47a1ebcbd
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/model/videollama2_mixtral.py b/VideoLLaMA2/videollama2/model/videollama2_mixtral.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbdeff33a526f25cce7a9e753aa9c559d81852ab
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/model/videollama2_qwen2.py b/VideoLLaMA2/videollama2/model/videollama2_qwen2.py
new file mode 100644
index 0000000000000000000000000000000000000000..419b7a632078488574050398f43b55aeca6e9b11
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/cli.py b/VideoLLaMA2/videollama2/serve/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..92c7cdd8685706bee8ce9c23bc00c7aa523fe505
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/controller.py b/VideoLLaMA2/videollama2/serve/controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5b0577948c30a9686234a81615883d8da72457d
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/examples/1034346401.mp4 b/VideoLLaMA2/videollama2/serve/examples/1034346401.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..cb132f0838c45014cdb6f7def631c510fe089293
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/examples/desert.jpg b/VideoLLaMA2/videollama2/serve/examples/desert.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..ac37c7fe071416a7f8a00f1b97bdf76ab6deb97c
--- /dev/null
+++ b/VideoLLaMA2/videollama2/serve/examples/desert.jpg
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d1f8133a0910fe8ccb40a410bcdced33a667427bb6e1f6c6de6348043af515d4
+size 880886
diff --git a/VideoLLaMA2/videollama2/serve/examples/extreme_ironing.jpg b/VideoLLaMA2/videollama2/serve/examples/extreme_ironing.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..638b078837f175039b2db49a63821288d9681daa
Binary files /dev/null and b/VideoLLaMA2/videollama2/serve/examples/extreme_ironing.jpg differ
diff --git a/VideoLLaMA2/videollama2/serve/examples/sample_demo_1.mp4 b/VideoLLaMA2/videollama2/serve/examples/sample_demo_1.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..a659cf1dc92142e24909bd17655ac47f9ac433db
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/examples/sample_demo_3.mp4 b/VideoLLaMA2/videollama2/serve/examples/sample_demo_3.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..4eb2c6b90edfd07f9161ac6f49b5ee6e04ebe1a6
--- /dev/null
+++ b/VideoLLaMA2/videollama2/serve/examples/sample_demo_3.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:da6126bce64c64a3d6f7ce889fbe15b5f1c2e3f978846351d8c7a79a950b429e
+size 463547
diff --git a/VideoLLaMA2/videollama2/serve/examples/sample_demo_9.mp4 b/VideoLLaMA2/videollama2/serve/examples/sample_demo_9.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..a0eeac56fbec64a564edf1e7ce62bf8aa22ed003
--- /dev/null
+++ b/VideoLLaMA2/videollama2/serve/examples/sample_demo_9.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f9702694f185e27ae016b85024b367e140cf93a4e3124d072816fd32f2ca0d96
+size 631864
diff --git a/VideoLLaMA2/videollama2/serve/examples/waterview.jpg b/VideoLLaMA2/videollama2/serve/examples/waterview.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..6f44ebaba1aa493b8bab3baa4e827b76752b1869
Binary files /dev/null and b/VideoLLaMA2/videollama2/serve/examples/waterview.jpg differ
diff --git a/VideoLLaMA2/videollama2/serve/gradio_web_server.py b/VideoLLaMA2/videollama2/serve/gradio_web_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..31ce1ab0938aa64ef450156ccc0ef753d20fcaaa
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/gradio_web_server_adhoc.py b/VideoLLaMA2/videollama2/serve/gradio_web_server_adhoc.py
new file mode 100644
index 0000000000000000000000000000000000000000..a539224389927b8ebfb0860ca299d2639ee7b646
--- /dev/null
+++ b/VideoLLaMA2/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.1-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()
diff --git a/VideoLLaMA2/videollama2/serve/model_worker.py b/VideoLLaMA2/videollama2/serve/model_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..630590459a4f720572f609b99c4ce848c12a424b
--- /dev/null
+++ b/VideoLLaMA2/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.builder import load_pretrained_model
+from videollama2.mm_utils import process_images, process_videos, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria, tokenizer_MMODAL_token
+from videollama2.mm_utils import chunk_list, frame_expansion
+from videollama2.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_TOKEN, NUM_FRAMES, MMODAL_TOKEN_INDEX
+
+
+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_images(images_or_videos, image_processor, model.config)
+
+ modal_list = ["image"]
+ replace_token = DEFAULT_IMAGE_TOKEN
+ modal_token_index = MMODAL_TOKEN_INDEX["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_videos(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_expansion(frame_list, 2) for frame_list in chunked_video_frames]
+ images_or_videos = process_videos(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_videos(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 = MMODAL_TOKEN_INDEX["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_images(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_MMODAL_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/videollama2/serve/register_worker.py b/VideoLLaMA2/videollama2/serve/register_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5385a800d5ae62ce11528b69816391c6831da7
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/sglang_worker.py b/VideoLLaMA2/videollama2/serve/sglang_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9a47fcf588ff0c2763c9eeef0ac3c4cfda20ea1
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/serve/test_message.py b/VideoLLaMA2/videollama2/serve/test_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1a88a1d8547d867f1b22cbd8ced9e5762ada01e
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2/train.py b/VideoLLaMA2/videollama2/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da3d6ebf0a2002d4cdee71fbfb6b28e724ec0d3
--- /dev/null
+++ b/VideoLLaMA2/videollama2/train.py
@@ -0,0 +1,574 @@
+# 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: List[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)
+ # 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
+
+ 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 = []
+ for dp in data_path:
+ _datas = json.load(open(dp, "r"))
+ list_data_dict.extend(_datas)
+
+ 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,
+ 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,
+ 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,
+ 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
+ # vision_tower is not trainable in VideoLLaMA2
+ model.get_model().vision_tower.requires_grad_(False)
+
+ 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("flash_attention_2")
diff --git a/VideoLLaMA2/videollama2/utils.py b/VideoLLaMA2/videollama2/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..20bd62a30d43310af655475081e0a38798635160
--- /dev/null
+++ b/VideoLLaMA2/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/videollama2_trainer.py b/VideoLLaMA2/videollama2/videollama2_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..802b3d6dc5142355c3d1c4d7ada02bece4e2897a
--- /dev/null
+++ b/VideoLLaMA2/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)