Commit fef630ee authored by suily's avatar suily
Browse files

init

parents
Pipeline #1942 failed with stages
in 0 seconds
**/__pycache__
checkpoints/
.ipynb_checkpoints/
wandb/
THU-Cloud-Downloader/
data/
feat/
backup/
proxy.sh
\ No newline at end of file
Attribution-NonCommercial-NoDerivatives 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-NoDerivatives 4.0 International Public
License ("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
c. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
d. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
e. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
f. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
g. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
h. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce and reproduce, but not Share, Adapted Material
for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material, You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under
this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only and provided You do not Share Adapted Material;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
# VTimeLLM
## 论文
`VTimeLLM: Empower LLM to Grasp Video Moments`
- https://arxiv.org/abs/2311.18445
## 模型结构
VTimeLLM有以下两个部分组成:1、一个视觉编码器和一个视觉适配器来处理输入视频;2、 一个特制的LLM过三阶段预训练来使模型同时具有grounding和chat能力
阶段一:图文对齐,通过图片-文本对训练将视觉特征与LLM在语义空间对齐;
阶段二:设计了密集Video Caption的单轮QA任务和包括片段描述&时序grounding的多轮的QA任务,使VTimeLLM具有时序感知的能力,可以定位视频的segmentation;
阶段三:创造了一个高质量的对话数据集来指令微调,来和人类意图对齐。
<div align=center>
<img src="./doc/VTimeLLM.PNG"/>
</div>
## 算法原理
Visual Encoder:利用CLIP ViT-L/14模型对每一帧获取cls token的feature和每个patch的feature,其中采用cls token的特征v_cls作为图片的feature
Visual Adapter:一个线性层,对每一帧的v_cls做变换,映射到LLM空间,最后视频由N*d的特征Z表示(N为帧数,d为LLM的隐层维度),这里均匀采样100帧
Vicuna:即LLM,用<video>来代表视频内容,将视觉特征Z嵌入到text的embedding中间
<div align=center>
<img src="./doc/ExpNet.PNG"/>
</div>
<div align=center>
<img src="./doc/PoseVAE.PNG"/>
</div>
<div align=center>
<img src="./doc/FaceRender.PNG"/>
</div>
## 环境配置
### Docker(方法一)
```
docker pull image.sourcefind.cn:5000/dcu/admin/base/jupyterlab-pytorch:2.1.0-ubuntu20.04-dtk24.04.2-py3.8
docker run -it --name=SadTalker --network=host --privileged=true --device=/dev/kfd --device=/dev/dri --shm-size=16G --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v /path/your_code_data:/path/SadTalker -v /opt/hyhal/:/opt/hyhal/:ro <imageID> bash # <imageID>为以上拉取的docker的镜像ID替换
cd SadTalker
# 安装ffmpeg:格式转换相关
apt update
apt install ffmpeg
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install tb-nightly -i https://mirrors.aliyun.com/pypi/simple
pip install -r requirements.txt
```
### Dockerfile(方法二)
```
docker build --no-cache -t sadtalker:latest .
docker run -it --name=SadTalker --network=host --privileged=true --device=/dev/kfd --device=/dev/dri --shm-size=16G --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v /path/your_code_data:/path/SadTalker -v /opt/hyhal/:/opt/hyhal/:ro sadtalker /bin/bash
cd SadTalker
# 安装ffmpeg:格式转换相关
apt update
apt install ffmpeg
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install tb-nightly -i https://mirrors.aliyun.com/pypi/simple
pip install -r requirements.txt
```
### Anaconda(方法三)
1、关于本项目DCU显卡所需的特殊深度学习库可从光合开发者社区下载安装: https://developer.hpccube.com/tool/
```
DTK软件栈:dtk24.04.2
python:python3.8
pytorch:2.1.0
torchvision:
torchaudio:
```
`Tips:以上dtk软件栈、python、pytorch等DCU相关工具版本需要严格一一对应`
2、其他非特殊库直接按照下面步骤进行安装
```
cd SadTalker
# 安装ffmpeg:格式转换相关
apt update
apt install ffmpeg
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install tb-nightly -i https://mirrors.aliyun.com/pypi/simple
pip install -r requirements.txt
```
## 数据集
推理测试所用数据已保存在SadTalker/dataset/下,目录结构如下:
```
── dataset
│   ├── bus_chinese.wav
│   └── image.png
```
## 训练
官方暂未开放
## 推理
模型可通过[scnet](http://113.200.138.88:18080/aimodels/findsource-dependency/sadtalker)或以下方式进行下载:
1-1、Pre-Trained Models
* [Google Drive](https://drive.google.com/file/d/1gwWh45pF7aelNP_P78uDJL8Sycep-K7j/view?usp=sharing)
* [GitHub Releases](https://github.com/OpenTalker/SadTalker/releases)
* [Baidu (百度云盘)](https://pan.baidu.com/s/1kb1BCPaLOWX1JJb9Czbn6w?pwd=sadt) (Password: `sadt`)
1-2、GFPGAN Offline Patch
* [Google Drive](https://drive.google.com/file/d/19AIBsmfcHW6BRJmeqSFlG5fL445Xmsyi?usp=sharing)
* [GitHub Releases](https://github.com/OpenTalker/SadTalker/releases)
* [Baidu (百度云盘)](https://pan.baidu.com/s/1P4fRgk9gaSutZnn8YW034Q?pwd=sadt) (Password: `sadt`)
2、运行自动下载(GitHub Releases):
```
cd SadTalker
sh scripts/download_models.sh
```
模型目录结构如下,checkpoints是预训练模型,gfpgan是人脸检测和增强模型:
```
── checkpoints
│   └── ...
── gfpgan
│   └── weights
│    └── ...
```
推理运行代码:
```
HIP_VISIBLE_DEVICES=0 python inference.py \
--driven_audio dataset/bus_chinese.wav \
--source_image dataset/image.png \
--still \
--preprocess full \
--enhancer gfpgan \
--result_dir result/
# --driven_audio 音频数据的路径
# --source_image 图片数据的路径
# --still 使用与原始图像相同的姿势参数,头部运动较少
# --preprocess full 对图像进行['crop', 'extcrop', 'resize', 'full', 'extfull']预处理
# --enhancer 使用或通过人脸修复网络[gfpgan, RestoreFormer]增强生成的人脸
# --result_dir 输出路径
# 更多参数设置可参考inference.py的parser注释和docs/best_practice.md
```
## result
推理运行的默认推理结果为:
<div align=center>
<video src="./doc/inference_result.mp4"/>
</div>
### 精度
## 应用场景
### 算法类别
`视频生成`
### 热点应用行业
`家具,电商,医疗,广媒,教育`
## 预训练权重
-
- http://113.200.138.88:18080/aimodels/vicuna-7b-v1.5.git (vicuna-7b-v1.5)
http://113.200.138.88:18080/aimodels/chatglm3-6b (chatglm3-6b)
## 源码仓库及问题反馈
-
## 参考资料
- https://github.com/huangb23/VTimeLLM
# VTimeLLM \[[Paper](https://arxiv.org/pdf/2311.18445.pdf)\]
Official PyTorch implementation of the paper "VTimeLLM: Empower LLM to Grasp Video Moments".
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance-4)](https://paperswithcode.com/sota/video-based-generative-performance-4?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/dense-video-captioning-on-activitynet)](https://paperswithcode.com/sota/dense-video-captioning-on-activitynet?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance-3)](https://paperswithcode.com/sota/video-based-generative-performance-3?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance-1)](https://paperswithcode.com/sota/video-based-generative-performance-1?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance-5)](https://paperswithcode.com/sota/video-based-generative-performance-5?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance-2)](https://paperswithcode.com/sota/video-based-generative-performance-2?p=vtimellm-empower-llm-to-grasp-video-moments)
[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/vtimellm-empower-llm-to-grasp-video-moments/video-based-generative-performance)](https://paperswithcode.com/sota/video-based-generative-performance?p=vtimellm-empower-llm-to-grasp-video-moments)
---
## :loudspeaker: Latest Updates
- **Jan-2**: Thanks to [Xiao Xia](https://github.com/Rishubi) , [Shengbo Tong](https://github.com/tsb-19) and [Beining Wang](https://github.com/Benson0704), we have refactored the code to now support both the LLAMA and ChatGLM3 architectures. We translated the training data into Chinese and fine-tuned a Chinese version based on the ChatGLM3-6b.
- **Dec-14**: Released the training code and data. All the resources including models, datasets and extracted features are available
[here](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2F&mode=list). :fire::fire:
- **Dec-4**: VTimeLLM: demo released.
---
## VTimeLLM Overview :bulb:
VTimeLLM is a novel Video LLM designed for fine-grained video moment understanding and reasoning with respect to time boundary.
VTimeLLM adopts a boundary-aware three-stage training strategy, which respectively utilizes image-text pairs for feature alignment, multiple-event videos to increase temporal-boundary awareness, and high-quality video-instruction tuning to further improve temporal understanding ability as well as align with human intents.
![framework](images/framework.png)
---
## Contributions :trophy:
- We propose VTimeLLM, the first boundary-aware Video LLM, to the best of our knowledge.
- We propose the boundary-aware three-stage training strategy, which consecutively leverages i) large-scale image-text data for feature alignment, ii) large-scale multi-event video-text data together with the temporal-related single-turn and multi-turn QA to enhance the awareness of time boundary, and iii) instruction tuning on the high-quality dialog dataset for better temporal reasoning ability.
- We conduct extensive experiments to demonstrate that the proposed VTimeLLM significantly outperforms existing Video LLMs in various fine-grained temporal-related video tasks, showing its superior ability for video understanding and reasoning.
---
## Installation :wrench:
We recommend setting up a conda environment for the project:
```shell
conda create --name=vtimellm python=3.10
conda activate vtimellm
git clone https://github.com/huangb23/VTimeLLM.git
cd VTimeLLM
pip install -r requirements.txt
```
Additionally, install additional packages for training cases.
```shell
pip install ninja
pip install flash-attn --no-build-isolation
```
## Running Demo Offline :cd:
To run the demo offline, please refer to the instructions in [offline_demo.md](docs/offline_demo.md).
## Training :train:
For training instructions, check out [train.md](docs/train.md).
## Qualitative Analysis :mag:
A Comprehensive Evaluation of VTimeLLM's Performance across Multiple Tasks.
### Video Understanding and Conversational Tasks :speech_balloon:
![0](images/ex.png)
---
### Creative Tasks :paintbrush:
![1](images/ex1.png)
---
### Fine-grained Understanding Tasks :globe_with_meridians:
![2](images/ex2.png)
---
### Video Reasoning Tasks :question:
![3](images/ex3.png)
---
## Acknowledgements :pray:
We are grateful for the following awesome projects our VTimeLLM arising from:
* [LLaVA](https://github.com/haotian-liu/LLaVA): Large Language and Vision Assistant
* [FastChat](https://github.com/lm-sys/FastChat): An Open Platform for Training, Serving, and Evaluating Large Language Model based Chatbots
* [Video-ChatGPT](https://github.com/mbzuai-oryx/Video-ChatGPT): Towards Detailed Video Understanding via Large Vision and Language Models
* [LLaMA](https://github.com/facebookresearch/llama): Open and Efficient Foundation Language Models
* [Vid2seq](https://github.com/google-research/scenic/tree/main/scenic/projects/vid2seq): Large-Scale Pretraining of a Visual Language Model for Dense Video Captioning
* [InternVid](https://github.com/OpenGVLab/InternVideo/tree/main/Data/InternVid): A Large-scale Video-Text dataset
If you're using VTimeLLM in your research or applications, please cite using this BibTeX:
```bibtex
@inproceedings{huang2024vtimellm,
title={Vtimellm: Empower llm to grasp video moments},
author={Huang, Bin and Wang, Xin and Chen, Hong and Song, Zihan and Zhu, Wenwu},
booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
pages={14271--14280},
year={2024}
}
```
## License :scroll:
<a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/80x15.png" /></a>
This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">Creative Commons Attribution-NonCommercial-NoDerivs 4.0 International License</a>.
Looking forward to your feedback, contributions, and stars! :star2:
Our dataset can be downloaded from [here](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fdata&mode=list). The data is organized in the following JSON format:
* source: The original sources of the dataset. This field is ['internvid'](https://huggingface.co/datasets/OpenGVLab/InternVid) in stage 2 and ['anet'](http://activity-net.org/download.html) or ['didemo'](https://drive.google.com/drive/u/0/folders/1_oyJ5rQiZboipbMl6tkhY8v0s9zDkvJc) in stage 3.
* id: The ID of the video in the original dataset.
* conversations: The conversation data used for training. We utilize special tokens (such as `<s0>`, `<e0>`) to indicate timestamps. These need to be replaced during training using information from the 'meta' field.
* meta:
* split: refers to the extraction of a segment from the original video as input, with two numbers denoting the start and end timestamps of the extraction. If this field does not exist, the entire video is used as input.
* duration: indicates the length of the input video.
* token: represents the timestamp of special tokens appearing in 'conversations'.
Here is an example:
```json
{
"source": "internvid",
"id": "3n3oCNerzV0",
"conversations": [
{
"from": "human",
"value": "<video>\nI'd appreciate it if you could provide a detailed account of the events that occurred at different timestamps in the video."
},
{
"from": "gpt",
"value": "From <s0> to <e0>, woman is counting money with a pen on a white table. From <s1> to <e1>, two people shaking hands in front of a desk."
}
],
"meta": {
"split": [
129.8,
184.0
],
"duration": 54.2,
"token": {
"<s0>": 0,
"<e0>": 9.4,
"<s1>": 49.4,
"<e1>": 53.2
}
}
}
```
Due to Internvid's data being sourced from YouTube, the 'id' field provides the YouTube ID of the video. We download the [original video](https://www.youtube.com/watch?v=3n3oCNerzV0) and extract the segment from 129.8s to 184.0s as input.
If we sample $N=100$ frames as input, then `<s0>` should be replaced by $\frac{0}{54.2} * N = 00$, `<e0>` should be replaced by $\frac{9.4}{54.2} * N = 17$. and `<s1>` and `<e1>` should be replaced in a similar manner. Finally, in this example, the question from 'human' remains unchanged, while the 'answer' from 'gpt' is shown as below:
```
From 00 to 17, woman is counting money with a pen on a white table. From 91 to 98, two people shaking hands in front of a desk.
```
In the Stage 3 data, approximately 20k data originate from [VideoChatGPT](https://github.com/mbzuai-oryx/Video-ChatGPT). This subset of data does not contain special tokens and the 'meta' field.
# VTimeLLM-Vicuna Evaluation
We provide evaluation code for VTimeLLM-Vicuna on dense video captioning and temporal video grounding tasks. Before proceeding, you should be able to run the inference code (refer to [offline_demo.md](offline_demo.md)). Below, we outline the evaluation process using the [ActivityNet Captions](https://cs.stanford.edu/people/ranjaykrishna/densevid/) dataset as an example.
- Download the annotation JSON file for the dataset. For the ActivityNet Captions dataset, the test set annotation file is `val_2.json`. For other datasets, you need to preprocess them to match the JSON format of this dataset.
- Download the raw videos of the dataset and store them in a specific folder.
- (Optional) Pre-extract video features (refer to inference.py) and store them in a specific folder. (For the ActivityNet Captions dataset, we have extracted features for approximately 80% of the test set videos, placed in the [feat folder of the stage3 training](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Ffeat&mode=list). You can use them for incomplete testing.)
- Run the evaluation code, and record the model's responses in a log file. (Specify at least one of `feat_folder` and `video_folder`) :
```bash
python vtimellm/eval/eval.py \
--data_path /path/to/val_2.json \
--feat_folder /path/to/feat \
--video_folder /path/to/video \
--log_path /path/to/log \
--model_base <path to the Vicuna v1.5 weights>
```
* In order to compute metrics for the dense video captioning task, you need to install `pycocoevalcap` and `Java`.
```bash
pip install pycocoevalcap
conda install conda-forge::openjdk
```
* Parse the log file and obtain the corresponding metrics.
```bash
python vtimellm/eval/metric.py \
--data_path /path/to/val_2.json \
--log_path /path/to/log
```
\ No newline at end of file
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "6401fb4e-c559-49e5-bc88-874a74dd54c4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"root_dir = os.path.join(os.getcwd(), \"..\")\n",
"import sys\n",
"sys.path.append(root_dir)\n",
"from vtimellm.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN\n",
"from vtimellm.conversation import conv_templates, SeparatorStyle\n",
"from vtimellm.model.builder import load_pretrained_model, load_lora\n",
"from vtimellm.utils import disable_torch_init\n",
"from vtimellm.mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, VideoExtractor\n",
"from PIL import Image\n",
"import requests\n",
"from io import BytesIO\n",
"from transformers import TextStreamer\n",
"from easydict import EasyDict as edict\n",
"try:\n",
" from torchvision.transforms import InterpolationMode\n",
" BICUBIC = InterpolationMode.BICUBIC\n",
"except ImportError:\n",
" from PIL import Image\n",
" BICUBIC = Image.BICUBIC\n",
"from torchvision.transforms import Compose, Resize, CenterCrop, Normalize\n",
"import numpy as np\n",
"import clip\n",
"import torch"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "a05c755d-ae5c-4e93-ae6f-4e4a6e795b14",
"metadata": {},
"outputs": [],
"source": [
"args = edict()\n",
"args.model_base = \"/path/to/vicuna-7b-v1.5\"\n",
"args.clip_path = os.path.join(root_dir, \"checkpoints/clip/ViT-L-14.pt\")\n",
"args.pretrain_mm_mlp_adapter = os.path.join(root_dir, \"checkpoints/vtimellm-vicuna-v1-5-7b-stage1/mm_projector.bin\")\n",
"args.stage2 = os.path.join(root_dir, \"checkpoints/vtimellm-vicuna-v1-5-7b-stage2\")\n",
"args.stage3 = os.path.join(root_dir, \"checkpoints/vtimellm-vicuna-v1-5-7b-stage3\")\n",
"args.video_path = os.path.join(root_dir, \"images/demo.mp4\")\n",
"args.temperature = 0.05"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d3815e10-d5a5-4fdf-a98f-ae9050f23b97",
"metadata": {},
"outputs": [],
"source": [
"def inference(model, tokenizer, context_len, image, args):\n",
" conv = conv_templates['v1'].copy()\n",
" roles = conv.roles\n",
" first = True\n",
" while True:\n",
" try:\n",
" inp = input(f\"{roles[0]}: \")\n",
" except EOFError:\n",
" inp = \"\"\n",
" if not inp:\n",
" print(\"exit...\")\n",
" break\n",
"\n",
" print(f\"{roles[1]}: \", end=\"\")\n",
"\n",
" if first:\n",
" # first message\n",
" inp = DEFAULT_IMAGE_TOKEN + '\\n' + inp\n",
" conv.append_message(conv.roles[0], inp)\n",
" first = False\n",
" else:\n",
" # later messages\n",
" conv.append_message(conv.roles[0], inp)\n",
" conv.append_message(conv.roles[1], None)\n",
" prompt = conv.get_prompt()\n",
"\n",
" input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()\n",
" stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 # plain:sep(###) v1:sep2(None)\n",
" keywords = [stop_str]\n",
" stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)\n",
" streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
"\n",
" with torch.inference_mode():\n",
" output_ids = model.generate(\n",
" input_ids,\n",
" images=image[None,].cuda(),\n",
" do_sample=True,\n",
" temperature=args.temperature,\n",
" max_new_tokens=1024,\n",
" streamer=streamer,\n",
" use_cache=True,\n",
" stopping_criteria=[stopping_criteria]\n",
" )\n",
"\n",
" outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()\n",
" conv.messages[-1][-1] = outputs"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a29e94ff-620e-4c86-adee-47206b67b606",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"You are using a model of type llama to instantiate a model of type VTimeLLM. This is not supported for all configurations of models and can yield errors.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Loading VTimeLLM from base model...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8c13771904c8424abf87e3e2507e4bd8",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Loading checkpoint shards: 0%| | 0/2 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/bhuang/miniconda3/envs/vtime/lib/python3.10/site-packages/transformers/generation/configuration_utils.py:381: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.9` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`. This was detected when initializing the generation config instance, which means the corresponding file may hold incorrect parameterization and should be fixed.\n",
" warnings.warn(\n",
"/home/bhuang/miniconda3/envs/vtime/lib/python3.10/site-packages/transformers/generation/configuration_utils.py:386: UserWarning: `do_sample` is set to `False`. However, `top_p` is set to `0.6` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_p`. This was detected when initializing the generation config instance, which means the corresponding file may hold incorrect parameterization and should be fixed.\n",
" warnings.warn(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"load mlp: /DATA/DATANAS2/bhuang/link/gitlab/vtimellm/docs/../checkpoints/vtimellm-vicuna-v1-5-7b-stage1/mm_projector.bin\n",
"Loading stage2 weights...\n",
"Loading LoRA weights...\n",
"Merging stage2 weights...\n",
"Loading stage3 weights...\n",
"Loading LoRA weights...\n",
"Merging stage3 weights...\n"
]
}
],
"source": [
"disable_torch_init()\n",
"tokenizer, model, context_len = load_pretrained_model(args, args.stage2, args.stage3)\n",
"model = model.cuda()\n",
"model = model.to(torch.float16)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f8165baa-775b-4106-88aa-3c723bd97c12",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/bhuang/miniconda3/envs/vtime/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).\n",
" warnings.warn(\n"
]
}
],
"source": [
"clip_model, _ = clip.load(args.clip_path)\n",
"clip_model.eval()\n",
"clip_model = clip_model.cuda()\n",
"\n",
"video_loader = VideoExtractor(N=100)\n",
"_, images = video_loader.extract({'id': None, 'video': args.video_path})\n",
"\n",
"transform = Compose([\n",
" Resize(224, interpolation=BICUBIC),\n",
" CenterCrop(224),\n",
" Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),\n",
"])\n",
"\n",
"# print(images.shape) # <N, 3, H, W>\n",
"images = transform(images / 255.0)\n",
"images = images.to(torch.float16)\n",
"with torch.no_grad():\n",
" features = clip_model.encode_image(images.to('cuda'))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "010a986d-6121-43f2-9971-619472c0732c",
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"USER: Explain why this video is funny.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ASSISTANT: The video is funny because the bear is dancing to the music and moving its arms and legs in a funny way. The bear's movements are exaggerated and comical, making it difficult for the person to keep up with the beat. The bear's facial expressions and body language add to the humor of the video.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"USER: Is it a real bear?\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ASSISTANT: No, it is not a real bear. It is a costume worn by a person.\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"USER: \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"exit...\n"
]
}
],
"source": [
"inference(model, tokenizer, context_len, features, args)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef73e662-cab9-46fa-9df8-b45e2b1d9f5b",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "6401fb4e-c559-49e5-bc88-874a74dd54c4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"/DATA/DATANAS2/bhuang/link/gitlab/vtimellm/docs/..\n"
]
}
],
"source": [
"import os\n",
"os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n",
"root_dir = os.path.join(os.getcwd(), \"..\")\n",
"print(root_dir)\n",
"import sys\n",
"sys.path.append(root_dir)\n",
"\n",
"from vtimellm.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN\n",
"from vtimellm.conversation import conv_templates, SeparatorStyle\n",
"from vtimellm.model.builder import load_pretrained_model, load_lora\n",
"from vtimellm.train.dataset import preprocess_glm\n",
"from vtimellm.utils import disable_torch_init\n",
"from vtimellm.mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, VideoExtractor\n",
"from PIL import Image\n",
"import requests\n",
"from io import BytesIO\n",
"from transformers import TextStreamer\n",
"from easydict import EasyDict as edict\n",
"try:\n",
" from torchvision.transforms import InterpolationMode\n",
" BICUBIC = InterpolationMode.BICUBIC\n",
"except ImportError:\n",
" from PIL import Image\n",
" BICUBIC = Image.BICUBIC\n",
"from torchvision.transforms import Compose, Resize, CenterCrop, Normalize\n",
"import numpy as np\n",
"import clip\n",
"import torch"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a05c755d-ae5c-4e93-ae6f-4e4a6e795b14",
"metadata": {},
"outputs": [],
"source": [
"model_version = 'chatglm3-6b' # vicuna-v1-5-7b\n",
"args = edict()\n",
"args.model_base = \"/DATA/DATANAS2/bhuang/data/vicuna-7b-v1.5\"\n",
"if model_version == 'chatglm3-6b':\n",
" args.model_base = os.path.join(root_dir, 'checkpoints/' + model_version)\n",
"args.clip_path = os.path.join(root_dir, \"checkpoints/clip/ViT-L-14.pt\")\n",
"args.pretrain_mm_mlp_adapter = os.path.join(root_dir, f\"checkpoints/vtimellm-{model_version}-stage1/mm_projector.bin\")\n",
"args.stage2 = os.path.join(root_dir, f\"checkpoints/vtimellm-{model_version}-stage2\")\n",
"args.stage3 = os.path.join(root_dir, f\"checkpoints/vtimellm-{model_version}-stage3\")\n",
"args.temperature = 0.05"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7cb39bb4",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"You are using a model of type chatglm to instantiate a model of type VTimeLLM_ChatGLM. This is not supported for all configurations of models and can yield errors.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Loading VTimeLLM from base model...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "20832fd2d2a44b7f8d540c32069df157",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Loading checkpoint shards: 0%| | 0/7 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"load mlp: /DATA/DATANAS2/bhuang/link/gitlab/vtimellm/docs/../checkpoints/vtimellm-chatglm3-6b-stage1/mm_projector.bin\n",
"Loading stage2 weights...\n",
"Loading LoRA weights...\n",
"Merging stage2 weights...\n",
"Loading stage3 weights...\n",
"Loading LoRA weights...\n",
"Merging stage3 weights...\n"
]
}
],
"source": [
"disable_torch_init()\n",
"tokenizer, model, context_len = load_pretrained_model(args, args.stage2, args.stage3)\n",
"model = model.cuda()\n",
"model = model.to(torch.float16)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "f8165baa-775b-4106-88aa-3c723bd97c12",
"metadata": {},
"outputs": [],
"source": [
"clip_model, _ = clip.load(args.clip_path)\n",
"clip_model.eval()\n",
"clip_model = clip_model.cuda()\n",
"\n",
"video_loader = VideoExtractor(N=100)\n",
"\n",
"transform = Compose([\n",
" Resize(224, interpolation=BICUBIC),\n",
" CenterCrop(224),\n",
" Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),\n",
"])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b0038bac",
"metadata": {},
"outputs": [],
"source": [
"args.video_path = '/DATA/DATANAS2/bhuang/link/1.mp4'\n",
"_, images = video_loader.extract({'id': None, 'video': args.video_path})\n",
"# print(images.shape) # <N, 3, H, W>\n",
"images = transform(images / 255.0)\n",
"images = images.to(torch.float16)\n",
"with torch.no_grad():\n",
" features = clip_model.encode_image(images.to('cuda'))"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "7b42d546",
"metadata": {},
"outputs": [],
"source": [
"def inference(model, tokenizer, context_len, image, args):\n",
" source = []\n",
" first = True\n",
" while True:\n",
" try:\n",
" inp = input(f\"USER: \")\n",
" except EOFError:\n",
" inp = \"\"\n",
" if not inp:\n",
" print(\"exit...\")\n",
" break\n",
"\n",
" print(f\"ASSISTANT:\", end=\"\")\n",
"\n",
" if first:\n",
" # first message\n",
" inp = DEFAULT_IMAGE_TOKEN + '\\n' + inp\n",
" first = False\n",
" \n",
" source.append({\n",
" 'from': \"human\",\n",
" 'value': inp\n",
" })\n",
" input_ids = preprocess_glm([source], tokenizer)['input_ids'].cuda()\n",
" input_ids[0][-1] = tokenizer.get_command(\"<|assistant|>\")\n",
" streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)\n",
"\n",
" with torch.inference_mode():\n",
" output_ids = model.generate(\n",
" input_ids,\n",
" images=image[None,].cuda(),\n",
" do_sample=True,\n",
" temperature=args.temperature,\n",
" max_new_tokens=1024,\n",
" streamer=streamer,\n",
" use_cache=True,\n",
" eos_token_id=[tokenizer.get_command(\"<|user|>\"), tokenizer.eos_token_id],\n",
" )\n",
"\n",
" outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:-1]).strip()\n",
" # print(outputs)\n",
" source.append({\n",
" 'from': \"gpt\",\n",
" 'value': outputs\n",
" })"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "010a986d-6121-43f2-9971-619472c0732c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ASSISTANT:视频中,一名男子在黑暗的房间里,手里拿着一个装满东西的盒子。他打开盒子,里面装满了各种物品。然后,该男子爬上一座高高的建筑物,并从窗户跳入水中。<|user|>\n",
"exit...\n"
]
}
],
"source": [
"inference(model, tokenizer, context_len, features, args)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ef73e662-cab9-46fa-9df8-b45e2b1d9f5b",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
# Running VTimeLLM inference Offline
Please follow the instructions below to run the VTimeLLM inference on your local GPU machine.
Note: Our demo requires approximately 18 GB of GPU memory.
### Clone the VTimeLLM repository
```shell
conda create --name=vtimellm python=3.10
conda activate vtimellm
git clone https://github.com/huangb23/VTimeLLM.git
cd VTimeLLM
pip install -r requirements.txt
```
### Download weights
* Download clip model and vtimellm model from the [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fcheckpoints&mode=list) and place them into the 'checkpoints' directory.
* Download [Vicuna v1.5](https://huggingface.co/lmsys/vicuna-7b-v1.5) or [ChatGLM3-6b](https://huggingface.co/THUDM/chatglm3-6b) weights.
### Run the inference code
```shell
python -m vtimellm.inference --model_base <path to the Vicuna v1.5 weights>
```
Alternatively, you can also choose to conduct multi-turn conversations in [Jupyter Notebook](inference.ipynb). Similarly, you need to set 'args.model_base' to the path of Vicuna v1.5.
If you want to run the VTimeLLM-ChatGLM version, please refer to the code in [inference_for_glm.ipynb](inference_for_glm.ipynb).
### Run the gradio demo
We have provided an offline gradio demo as follows:
```shell
cd vtimellm
python demo_gradio.py --model_base <path to the Vicuna v1.5 weights>
```
# Training VTimeLLM
VTimeLLM adopts a three-stage training strategy. Please follow the instructions below to train VTimeLLM-7B model.
* Download [clip](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fcheckpoints&mode=list) and [Vicuna v1.5](https://huggingface.co/lmsys/vicuna-7b-v1.5) weights, and place them into the 'checkpoints' directory.
* Download stage1 dataset from [this link](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json), and download stage2 and stage3 dataset from the [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fdata&mode=list). Place them into the 'data' directory.
```markdown
- VTimeLLM
- checkpoints
- clip
- ViT-L-14.pt
- vicuna-7b-v1.5
- pytorch_model-00001-of-00002.bin
- ...
- data
- blip_laion_cc_sbu_558k.json
- stage2.json
- stage3.json
- scripts
- stage1.sh
- stage2.sh
- stage3.sh
- ...
- vtimellm
- ...
```
If you want to train a Chinese version, you can download the [ChatGLM3-6b](https://huggingface.co/THUDM/chatglm3-6b) model and the translated Chinese [dataset](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fdata&mode=list).
* Download the pre-extracted features from the [Tsinghua Cloud](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Ffeat&mode=list).
```shell
tar -xzvf stage1.tar.gz
cat stage2_part_* > stage2.tar.gz
tar -xzvf stage2.tar.gz
tar -xzvf stage3.tar.gz
```
* Train in three stages sequentially, and make sure to modify '--feat_folder' in the script to the corresponding feature folder for each stage.
```shell
cd VTimeLLM
bash scripts/stage1.sh
bash scripts/stage2.sh
bash scripts/stage3.sh
```
\ No newline at end of file
File added
# torch
# flash-attn
# torchvision
# deepspeed
decord
easydict
einops
gradio
numpy
pandas>=2.0.3
peft>=0.4.0
Pillow
tqdm
transformers==4.31.0
git+https://github.com/openai/CLIP.git
sentencepiece
protobuf
wandb
ninja
huggingface_hub
#!/bin/bash
MODEL_VERSION=vicuna-v1-5-7b
gpu_vis=0,1 # per_device_train_batch_size * gradient_accumulation_steps * n_gpus = 128
MASTER_PORT=29029
deepspeed --include localhost:$gpu_vis --master_port $MASTER_PORT vtimellm/train/train_mem.py \
--deepspeed ./scripts/zero3.json \
--model_name_or_path ./checkpoints/vicuna-7b-v1.5 \
--version plain \
--data_path ./data/blip_laion_cc_sbu_558k.json \
--feat_folder ./feat/558k_clip_feat \
--tune_mm_mlp_adapter True \
--output_dir ./checkpoints/vtimellm-$MODEL_VERSION-stage1_test \
--bf16 True \
--num_train_epochs 1 \
--per_device_train_batch_size 16 \
--gradient_accumulation_steps 4 \
--evaluation_strategy "no" \
--save_strategy "steps" \
--save_steps 200 \
--save_total_limit 1 \
--learning_rate 1e-3 \
--weight_decay 0. \
--warmup_ratio 0.03 \
--lr_scheduler_type "cosine" \
--tf32 True \
--logging_steps 1 \
--model_max_length 2048 \
--gradient_checkpointing True \
--dataloader_num_workers 4 \
--lazy_preprocess True \
--report_to wandb
\ No newline at end of file
#!/bin/bash
MODEL_VERSION=chatglm3-6b
gpu_vis=0 # per_device_train_batch_size * gradient_accumulation_steps * n_gpus = 128
MASTER_PORT=29570
deepspeed --include localhost:$gpu_vis --master_port $MASTER_PORT vtimellm/train/train.py \
--deepspeed ./scripts/zero3.json \
--model_name_or_path ./checkpoints/$MODEL_VERSION \
--version plain \
--data_path ./data/blip_laion_cc_sbu_558k_chinese.json \
--feat_folder /path/to/stage1_feat \
--tune_mm_mlp_adapter True \
--output_dir ./checkpoints/vtimellm-$MODEL_VERSION-stage1 \
--bf16 True \
--num_train_epochs 1 \
--per_device_train_batch_size 16 \
--gradient_accumulation_steps 8 \
--evaluation_strategy "no" \
--save_strategy "steps" \
--save_steps 24000 \
--save_total_limit 1 \
--learning_rate 1e-3 \
--weight_decay 0. \
--warmup_ratio 0.03 \
--lr_scheduler_type "cosine" \
--logging_steps 1 \
--tf32 True \
--model_max_length 2048 \
--gradient_checkpointing True \
--dataloader_num_workers 4 \
--lazy_preprocess True \
--report_to wandb
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment