"vscode:/vscode.git/clone" did not exist on "841810f227d5c8c9385749df811272eebc8e5845"
Commit 3a0371d5 authored by suily's avatar suily
Browse files

Initial commit

parents
Pipeline #2002 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/VTimeLLM.PNG"/>
</div>
## 环境配置
### Docker(方法一)
```
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.1.0-ubuntu20.04-dtk24.04.2-py3.10
docker run -it --name=VTimeLLM --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/VTimeLLM -v /opt/hyhal/:/opt/hyhal/:ro <imageID> bash # <imageID>为以上拉取的docker的镜像ID替换
cd VTimeLLM
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r requirements.txt
export HF_ENDPOINT=https://hf-mirror.com
# 解决deepspeed的async_io报错
apt update
apt install gcc libaio-dev
```
### Dockerfile(方法二)
```
docker build --no-cache -t vtimellm:latest .
docker run -it --name=VTimeLLM --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/VTimeLLM -v /opt/hyhal/:/opt/hyhal/:ro vtimellm /bin/bash
cd VTimeLLM
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r requirements.txt
export HF_ENDPOINT=https://hf-mirror.com
# 解决deepspeed的async_io报错
apt update
apt install gcc libaio-dev
```
### Anaconda(方法三)
1、关于本项目DCU显卡所需的特殊深度学习库可从光合开发者社区下载安装: https://developer.hpccube.com/tool/
```
DTK软件栈:dtk24.04.2
python:python3.10
pytorch:2.1.0
torchvision:0.16.0
deepspeed:0.14.2
flash-attn:2.0.4
```
`Tips:以上dtk软件栈、python、pytorch等DCU相关工具版本需要严格一一对应`
2、其他非特殊库直接按照下面步骤进行安装
```
cd VTimeLLM
# 安装依赖
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install -r requirements.txt
export HF_ENDPOINT=https://hf-mirror.com
# 解决deepspeed的async_io报错
apt update
apt install gcc libaio-dev
```
### 手动修改代码:
deepspeed0.14.2只能使用transformers4.31.0,此版本不支持k100ai使用bf16/tf32精度,修改transformers代码,避免精度错误:
```
pip show pip #查看依赖库安装地址site-packages
1、site-packages/transformers/utils/import_utils.py,修改def is_torch_bf16_gpu_available()277行后:
...
#TODO:if torch.cuda.is_available() and torch.version.cuda is not None:
if torch.cuda.is_available():
if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
return False
# if int(torch.version.cuda.split(".")[0]) < 11:
# return False
if not hasattr(torch.cuda.amp, "autocast"):
return False
else:
return False
return True
2、site-packages/transformers/utils/import_utils.py,修改def is_torch_tf32_available()322行后:
...
#TODO:if not torch.cuda.is_available() or torch.version.cuda is None:
if not torch.cuda.is_available():
return False
if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
return False
# if int(torch.version.cuda.split(".")[0]) < 11:
# return False
if version.parse(version.parse(torch.__version__).base_version) < version.parse("1.7"):
return False
return True
```
## 数据集
### 训练数据集
VTimeLLM可基于Vicuna v1.5训练英文版本、基于ChatGLM3-6b训练中文版本,训练某个版本时只下载对应的数据集(data不同)即可。
训练数据集包括三阶段的数据集data和预提取特征feat两部分,完整数据集可通过[scnet](http://113.200.138.88:18080/aidatasets/project-dependency/vtimellm) 或官网链接进行下载。官网链接如下:
ps:本仓库内准备了小数据集供训练测试,位于VTimeLLM/feat、VTimeLLM/data。
1、下载data
(1)VTimeLLM-7B:
* [stage1.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json)
* [stage2.json](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/files/?p=%2Fdata%2Fstage2.json)
* [stage3.json](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/files/?p=%2Fdata%2Fstage3.json)
(2)ChatGLM3-6b:
* [stage1/2/3.json](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/files/?p=%2Fdata%2Fdata_Chinese.zip)
2、下载feat
* [feat_list](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Ffeat&mode=list)
解压缩feat的代码如下:
```
cd VTimeLLM/feat
tar -xzvf stage1.tar.gz
cat stage2_part_* > stage2.tar.gz
tar -xzvf stage2.tar.gz
tar -xzvf stage3.tar.gz
```
以基于VTimeLLM-7B的VTimeLLM为例,数据集目录结构如下:
```
VTimeLLM:
── data
│   ├── blip_laion_cc_sbu_558k.json
│   ├── stage2.json
│   └── stage3.json
── feat
│   ├── 558k_clip_feat
│   ├── intern_clip_feat
│   └── stage3_clip_feat
```
### 推理数据集
推理测试所用数据已保存在VTimeLLM/images/demo.mp4
## 训练
VTimeLLM可基于Vicuna v1.5训练英文版本、基于ChatGLM3-6b训练中文版本,训练某个版本时只下载对应的模型即可。
训练需要分别下载clip、Vicuna v1.5(或ChatGLM3-6b)权重,并将它们放入 'checkpoints' 目录中,下载链接如下:
1、下载cilp模型
* [scnet](http://113.200.138.88:18080/aimodels/findsource-dependency/vtimellm)
* [官网链接](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fcheckpoints&mode=list)
2-1、下载Vicuna v1.5权重
* [scnet](http://113.200.138.88:18080/aimodels/vicuna-7b-v1.5)
* [官网链接](https://huggingface.co/lmsys/vicuna-7b-v1.5/tree/main)
* 代码下载(huggingface)
```
cd VTimeLLM
export HF_ENDPOINT=https://hf-mirror.com
export HF_DATASETS_CACHE="./checkpoints/vicuna-7b-v1.5"
huggingface-cli download --resume-download lmsys/vicuna-7b-v1.5 --local-dir checkpoints/vicuna-7b-v1.5 --local-dir-use-symlinks False
```
2-2、下载ChatGLM3-6b权重
* [scnet](http://113.200.138.88:18080/aimodels/chatglm3-6b)
* [官网链接](https://huggingface.co/THUDM/chatglm3-6b/tree/main)
* 代码下载(huggingface)
```
cd VTimeLLM
export HF_ENDPOINT=https://hf-mirror.com
export HF_DATASETS_CACHE="./checkpoints/chatglm3-6b"
huggingface-cli download --resume-download THUDM/chatglm3-6b --local-dir checkpoints/chatglm3-6b --local-dir-use-symlinks False
```
以基于VTimeLLM-7B的VTimeLLM为例,模型目录结构如下:
```
VTimeLLM/checkpoints:
── clip
│   └── ViT-L-14.pt
── vicuna-7b-v1.5
│   └── ...
```
以基于Vicuna v1.5的VTimeLLM为例,训练运行代码:
```
# 若使用小数据集需修改sh文件,例如per_device_train_batch_size=gradient_accumulation_steps=2【per_device_train_batch_size*n_gpus<10不能超过小数据集的size】
cd VTimeLLM
wandb off
sh scripts/stage1.sh
sh scripts/stage2.sh
sh scripts/stage3.sh
```
## 推理
VTimeLLM基于Vicuna v1.5训练了英文版本,存储为vtimellm-vicuna-v1-5-7b.tar.gz;基于ChatGLM3-6b训练了中文版本,存储为vtimellm-chatglm3-6b.tar.gz。推理某个版本时只下载对应的模型即可。
推理需要分别下载clip、Vicuna v1.5(或ChatGLM3-6b)、VTimeLLM权重,并将它们放入 'checkpoints' 目录中。clip、Vicuna v1.5(或ChatGLM3-6b)的下载参考训练阶段,VTimeLLM权重的下载链接如下:
* [scnet](http://113.200.138.88:18080/aimodels/findsource-dependency/vtimellm)
* [官网链接](https://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fcheckpoints&mode=list)
解压VTimeLLM权重的代码如下:
```
cd VTimeLLM/checkpoints
tar -xzvf vtimellm-vicuna-v1-5-7b.tar.gz
# tar -xzvf vtimellm-chatglm3-6b.tar.gz
```
以基于Vicuna v1.5的VTimeLLM为例,模型目录结构如下:
```
VTimeLLM/checkpoints:
── clip
│   └── ViT-L-14.pt
── vtimellm-vicuna-v1-5-7b-stage1
│   └── ...
── vtimellm-vicuna-v1-5-7b-stage2
│   └── ...
── vtimellm-vicuna-v1-5-7b-stage3
│   └── ...
── vicuna-7b-v1.5
│   └── ...
```
以基于Vicuna v1.5的VTimeLLM为例,推理运行代码:
```
cd VTimeLLM
HIP_VISIBLE_DEVICES=0 python -m vtimellm.inference \
--model_base "checkpoints/vicuna-7b-v1.5" \
--pretrain_mm_mlp_adapter "checkpoints/vtimellm-vicuna-v1-5-7b-stage1/mm_projector.bin" \
--stage2 "checkpoints/vtimellm-vicuna-v1-5-7b-stage2" \
--stage3 "checkpoints/vtimellm-vicuna-v1-5-7b-stage3" \
--video_path "images/demo.mp4"
```
推理VTimeLLM-ChatGLM版本,请参考VTimeLLM/docs/inference_for_glm.ipynb
## result
默认推理结果为:
<div align=center>
<img src="./doc/inference_result.png"/>
</div>
### 精度
以下为默认训练结果:
| | 测试参数 | 软件栈 | final loss |
| -------------------------------- | ------------------------------------------------ | ---------- | ---------- |
| A800 * 2<br/>(80G,1410 Mhz) | MODEL_VERSION=vicuna-v1-5-7b<br/>bf16=True<br/>tf32=True | cuda11.8 | stages1:2.415712<br/>stages2:1.046057<br/>stages3:1.283405 |
| k100ai * 2<br/>(64G,1500 Mhz) | MODEL_VERSION=vicuna-v1-5-7b<br/>bf16=True<br/>tf32=True | dtk24.04.2 | stages1:2.414052<br/>stages2:1.050350<br/>stages3:1.265567 |
## 应用场景
### 算法类别
`视频理解`
### 热点应用行业
`家具,电商,医疗,广媒,教育`
## 预训练权重
- http://113.200.138.88:18080/aimodels/findsource-dependency/vtimellm (vtimellm、clip)
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://cloud.tsinghua.edu.cn/d/6db5d02883124826aa6f/?p=%2Fcheckpoints&mode=list (vtimellm、clip)
https://huggingface.co/lmsys/vicuna-7b-v1.5/tree/main (vicuna-7b-v1.5)
https://huggingface.co/THUDM/chatglm3-6b/tree/main (chatglm3-6b)
## 源码仓库及问题反馈
- https://developer.sourcefind.cn/codes/suily/vtimellm_pytorch
## 参考资料
- 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:
[
{
"id": "004539375",
"image": "00453/004539375.jpg",
"conversations": [
{
"from": "human",
"value": "Render a clear and concise summary of the photo.\n<image>"
},
{
"from": "gpt",
"value": "select luxury furniture 3 - inch gel memory foam mattress topper"
}
]
},
{
"id": "002239345",
"image": "00223/002239345.jpg",
"conversations": [
{
"from": "human",
"value": "Write a terse but informative summary of the picture.\n<image>"
},
{
"from": "gpt",
"value": "a grey watch with an army style strap"
}
]
},
{
"id": "005947502",
"image": "00594/005947502.jpg",
"conversations": [
{
"from": "human",
"value": "<image>\nWhat is this?"
},
{
"from": "gpt",
"value": "a dragon kite flying in the blue sky stock images"
}
]
},
{
"id": "005116462",
"image": "00511/005116462.jpg",
"conversations": [
{
"from": "human",
"value": "<image>\nRender a clear and concise summary of the photo."
},
{
"from": "gpt",
"value": "$ 10 - cute cheap printed mini dress - khaki multicolor striped floral print peasant short sleeve tunic"
}
]
},
{
"id": "002017886",
"image": "00201/002017886.jpg",
"conversations": [
{
"from": "human",
"value": "What is in the photo?\n<image>"
},
{
"from": "gpt",
"value": "augmented reality using aruco markers in opencv"
}
]
},
{
"id": "001819539",
"image": "00181/001819539.jpg",
"conversations": [
{
"from": "human",
"value": "Describe the image concisely.\n<image>"
},
{
"from": "gpt",
"value": "a pair of childrens boots in the shape of knitted shoes"
}
]
},
{
"id": "002838027",
"image": "00283/002838027.jpg",
"conversations": [
{
"from": "human",
"value": "Share a concise interpretation of the image provided.\n<image>"
},
{
"from": "gpt",
"value": "floral watercolor clip art rose flower border with pink"
}
]
},
{
"id": "000406392",
"image": "00040/000406392.jpg",
"conversations": [
{
"from": "human",
"value": "Give a brief description of the image.\n<image>"
},
{
"from": "gpt",
"value": "the divine queen in her elaborate masks canvas print featuring the face and hands of a woman with red hair"
}
]
},
{
"id": "006288475",
"image": "00628/006288475.jpg",
"conversations": [
{
"from": "human",
"value": "<image>\nWhat is this?"
},
{
"from": "gpt",
"value": "an aerial view of paris at night from a plane stock photo"
}
]
},
{
"id": "000075539",
"image": "00007/000075539.jpg",
"conversations": [
{
"from": "human",
"value": "Give a brief description of the image.\n<image>"
},
{
"from": "gpt",
"value": "the nike air trainer low in desert tan and black"
}
]
}
]
\ No newline at end of file
[
{
"id": "Mq57LwS2UtI",
"conversations": [
{
"from": "human",
"value": "<video>\nCould you provide a summary of the incidents that occurred at various timestamps in the video?"
},
{
"from": "gpt",
"value": "A crowd of people watching an asian news broadcast from <s0> to <e0>. An image of the news, showing people at a church from <s1> to <e1>."
}
],
"meta": {
"split": [
77.3,
85.0
],
"duration": 7.7,
"token": {
"<s0>": 0,
"<e0>": 3.5,
"<s1>": 3.5,
"<e1>": 7.7
}
},
"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>": 54.2
}
},
"source": "internvid"
},
{
"id": "4vWt9kL3PJw",
"conversations": [
{
"from": "human",
"value": "<video>\nDuring which frames does a woman cutting pieces of paper that are colored occur in the video?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>."
},
{
"from": "human",
"value": "At which time interval in the video can we see a person uses scissors to cut off colorful straws occurring?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>."
}
],
"meta": {
"split": [
7.4,
74.7
],
"duration": 67.3,
"token": {
"<s0>": 37.6,
"<e0>": 44.6,
"<s1>": 48.6,
"<e1>": 58.4
}
},
"source": "internvid"
},
{
"id": "OfOYCsU-46s",
"conversations": [
{
"from": "human",
"value": "<video>\nCould you provide a summary of the incidents that occurred at various timestamps in the video?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>, chinese characters and white background on screen in a meeting. From <s1> to <e1>, a man in a business suit wearing a face mask is holding a laptop. From <s2> to <e2>, woman wearing face mask in restaurant. From <s3> to <e3>, a man and woman wearing a face mask in a chinese newscast."
}
],
"meta": {
"split": [
61.4,
114.5
],
"duration": 53.1,
"token": {
"<s0>": 0,
"<e0>": 3.4,
"<s1>": 10.0,
"<e1>": 17.9,
"<s2>": 40.6,
"<e2>": 44.3,
"<s3>": 49.3,
"<e3>": 53.1
}
},
"source": "internvid"
},
{
"id": "JYUqV-7BPWE",
"conversations": [
{
"from": "human",
"value": "<video>\nDescribe what took place from <s1> to <e1> in the video."
},
{
"from": "gpt",
"value": "A person holding a pair of keys and closing a window."
},
{
"from": "human",
"value": "Between which two frames can we witness the man is opening a window occurring in the video?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>."
}
],
"meta": {
"split": [
3.7,
27.2
],
"duration": 23.5,
"token": {
"<s0>": 4.0,
"<e0>": 9.6,
"<s1>": 9.6,
"<e1>": 15.0
}
},
"source": "internvid"
},
{
"id": "fjadWGRxWq4",
"conversations": [
{
"from": "human",
"value": "<video>\nAt what point in the video can we observe the xinhua video shows how a local chinese man enjoys the chinese new year taking place?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>."
},
{
"from": "human",
"value": "At which time interval in the video can we see an asian family gathered around a table eating some food occurring?"
},
{
"from": "gpt",
"value": "From <s2> to <e2>."
},
{
"from": "human",
"value": "Between which frames is chinese elderly people sit around the table, eating the food visible in the video?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>."
}
],
"meta": {
"split": [
132.5,
196.3
],
"duration": 63.8,
"token": {
"<s0>": 0,
"<e0>": 6.6,
"<s1>": 47.7,
"<e1>": 53.2,
"<s2>": 53.2,
"<e2>": 63.8
}
},
"source": "internvid"
},
{
"id": "xmWID6WCDfc",
"conversations": [
{
"from": "human",
"value": "<video>\nCould you provide a summary of the incidents that occurred at various timestamps in the video?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>, the google search page with a cartoon soccer player. From <s1> to <e1>, a chinese page showing an anime image. From <s2> to <e2>, a man playing soccer with a ball and some chinese words."
}
],
"meta": {
"split": [
33.7,
152.2
],
"duration": 118.5,
"token": {
"<s0>": 0,
"<e0>": 23.6,
"<s1>": 69.9,
"<e1>": 108.8,
"<s2>": 108.8,
"<e2>": 118.5
}
},
"source": "internvid"
},
{
"id": "WJL-njJOb2w",
"conversations": [
{
"from": "human",
"value": "<video>\nBetween which two frames can we witness bitcoins in stock exchange occurring in the video?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>."
},
{
"from": "human",
"value": "Share what transpired from <s0> to <e0> in the video."
},
{
"from": "gpt",
"value": "How to buy bitcoins with us dollars."
}
],
"meta": {
"split": [
39.1,
132.0
],
"duration": 92.9,
"token": {
"<s0>": 0,
"<e0>": 28.3,
"<s1>": 57.6,
"<e1>": 92.9
}
},
"source": "internvid"
},
{
"id": "oV2kjFLrXrw",
"conversations": [
{
"from": "human",
"value": "<video>\nDuring which frames can we see a man in a jacket sits on the edge of a chair happening in the video?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>."
},
{
"from": "human",
"value": "Provide details about the events from <s0> to <e0> in the video."
},
{
"from": "gpt",
"value": "The woman is wearing an old white dress in a cave."
}
],
"meta": {
"split": [
169.7,
221.9
],
"duration": 52.2,
"token": {
"<s0>": 32.3,
"<e0>": 38.8,
"<s1>": 46.3,
"<e1>": 51.6
}
},
"source": "internvid"
},
{
"id": "RnLq3gGn8_s",
"conversations": [
{
"from": "human",
"value": "<video>\nDuring which frames can we see a man speaking in korean happening in the video?"
},
{
"from": "gpt",
"value": "From <s2> to <e2>."
},
{
"from": "human",
"value": "At which time interval in the video can we see a man waving his hand with the words 'i am sanbae' occurring?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>."
},
{
"from": "human",
"value": "During which frames does a man is speaking in front of a crowd with green and yellow balloons occur in the video?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>."
}
],
"meta": {
"split": [
21.5,
48.4
],
"duration": 26.9,
"token": {
"<s0>": 0,
"<e0>": 5.8,
"<s1>": 8.3,
"<e1>": 13.5,
"<s2>": 13.5,
"<e2>": 17.8
}
},
"source": "internvid"
}
]
\ No newline at end of file
[
{
"id": "v_QOlSCBRmfWY",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat was the primary purpose of the video?"
},
{
"from": "gpt",
"value": "The primary purpose of the video appears to be showcasing the young woman's dance routine, highlighting her movements and expression while executing them."
},
{
"from": "human",
"value": "Can you pinpoint when the girl changes her pose or dance style?"
},
{
"from": "gpt",
"value": "From <s1> to <e1>, the girl transitions from one pose or dance style to another as the camera captures her movements."
},
{
"from": "human",
"value": "Is there any specific reason for the change in dance style or pose?"
},
{
"from": "gpt",
"value": "Based on the video content, there is no evident reason for the change in dance style or pose. It could be a creative decision by the videographer or an expression of the dancer's artistic expression."
}
],
"meta": {
"duration": 82.7,
"token": {
"<s0>": 0.8,
"<e0>": 19.9,
"<s1>": 17.4,
"<e1>": 60.8,
"<s2>": 56.3,
"<e2>": 79.4
}
},
"source": "anet"
},
{
"id": "v_QOlSCBRmfWY",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the main event portrayed in the video?"
},
{
"from": "gpt",
"value": "The primary event in the video is a young woman's dance, which takes place from <s0> to <e0>. She is shown standing in a room before transitioning into her dance, and the camera captures her movements throughout the dance."
},
{
"from": "human",
"value": "Can you provide more details about the dance itself?"
},
{
"from": "gpt",
"value": "Certainly! The young woman engages in a lively dance, moving around the room from <s1> to <e1>. Her movements showcase a range of emotions and expressions as she dances. The dance concludes with her lying on the floor from <s2> to <e2>."
},
{
"from": "human",
"value": "What is the mood of the video?"
},
{
"from": "gpt",
"value": "The mood of the video can be described as light-hearted and playful. The young woman's dance is energetic and expressive, suggesting a sense of joy and freedom."
}
],
"meta": {
"duration": 82.7,
"token": {
"<s0>": 0.8,
"<e0>": 19.9,
"<s1>": 17.4,
"<e1>": 60.8,
"<s2>": 56.3,
"<e2>": 79.4
}
},
"source": "anet"
},
{
"id": "v_ogQozSI5V8U",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the content of the video?"
},
{
"from": "gpt",
"value": "The video features a dog wearing socks, walking slowly on a wooden floor in a hallway, followed by the dog turning around and returning to another room."
},
{
"from": "human",
"value": "When does the dog walk out onto the wooden floor in the hallway?"
},
{
"from": "gpt",
"value": "The dog walks out onto the wooden floor from <s1> to <e1>."
}
],
"meta": {
"duration": 36.5,
"token": {
"<s0>": 0,
"<e0>": 7.5,
"<s1>": 7.5,
"<e1>": 18.1,
"<s2>": 19.4,
"<e2>": 36.5
}
},
"source": "anet"
},
{
"id": "v_ogQozSI5V8U",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the main event that takes place in the video?"
},
{
"from": "gpt",
"value": "The primary event in the video is a dog walking on a wooden floor wearing socks. The dog moves slowly from one room to another, turns around, and then walks back to the other room."
},
{
"from": "human",
"value": "Can you specify when the dog's socks become visible?"
},
{
"from": "gpt",
"value": "The dog's socks become visible from <s1> to <e1>."
}
],
"meta": {
"duration": 36.5,
"token": {
"<s0>": 0,
"<e0>": 7.5,
"<s1>": 7.5,
"<e1>": 18.1,
"<s2>": 19.4,
"<e2>": 36.5
}
},
"source": "anet"
},
{
"id": "v_69IsHpmRyfk",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you explain what's happening in the video?"
},
{
"from": "gpt",
"value": "The video features a young girl sitting in a chair, while an individual stands beside her. From <s0> to <e0>, we observe the person next to her piercing both of her ears with a piercing tool. Following this, from <s1> to <e1>, the person applies lotion to the newly pierced ears."
},
{
"from": "human",
"value": "Could you provide the timestamps for these events?"
},
{
"from": "gpt",
"value": "Certainly. The ear piercing takes place from <s0> to <e0>, and the lotion application occurs from <s1> to <e1>."
}
],
"meta": {
"duration": 94.7,
"token": {
"<s0>": 1.9,
"<e0>": 31.3,
"<s1>": 29.4,
"<e1>": 71.5,
"<s2>": 55.4,
"<e2>": 91.4
}
},
"source": "anet"
},
{
"id": "v_69IsHpmRyfk",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the primary action taking place in the video?"
},
{
"from": "gpt",
"value": "The primary action in the video is the piercing of the young girl's ears by a person standing next to her."
},
{
"from": "human",
"value": "Could you provide a timeline of the events?"
},
{
"from": "gpt",
"value": "Certainly. The events unfold as follows: from <s0> to <e0>, the girl is seated in a chair; from <s1> to <e1>, the person pierces one ear followed by the other; and from <s2> to <e2>, the person applies lotion to the piercings."
}
],
"meta": {
"duration": 94.7,
"token": {
"<s0>": 1.9,
"<e0>": 31.3,
"<s1>": 29.4,
"<e1>": 71.5,
"<s2>": 55.4,
"<e2>": 91.4
}
},
"source": "anet"
},
{
"id": "v_D18b2IZpxk0",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you briefly describe the video's content?"
},
{
"from": "gpt",
"value": "The video features a woman riding a camel while passing renowned pyramids in Egypt."
},
{
"from": "human",
"value": "What happens between <s1> and <e1>?"
},
{
"from": "gpt",
"value": "During that time, the woman leans forward while riding the camel."
},
{
"from": "human",
"value": "Is there any action captured between <s2> and <e2>?"
},
{
"from": "gpt",
"value": "Yes, a hand covers the lens as the camel's harness is shown."
}
],
"meta": {
"duration": 95.7,
"token": {
"<s0>": 0,
"<e0>": 17.7,
"<s1>": 19.6,
"<e1>": 88.0,
"<s2>": 90.9,
"<e2>": 95.7
}
},
"source": "anet"
},
{
"id": "v_D18b2IZpxk0",
"conversations": [
{
"from": "human",
"value": "<video>\nPlease describe the video's primary content."
},
{
"from": "gpt",
"value": "The video showcases a woman riding a camel in the presence of iconic Egyptian pyramids."
},
{
"from": "human",
"value": "Can you pinpoint when the woman leans forward on the camel?"
},
{
"from": "gpt",
"value": "Yes, the woman leans forward from <s1> to <e1>."
}
],
"meta": {
"duration": 95.7,
"token": {
"<s0>": 0,
"<e0>": 17.7,
"<s1>": 19.6,
"<e1>": 88.0,
"<s2>": 90.9,
"<e2>": 95.7
}
},
"source": "anet"
},
{
"id": "v_oP77DgsbhKQ",
"conversations": [
{
"from": "human",
"value": "<video>\nPlease provide a summary of the video's content."
},
{
"from": "gpt",
"value": "Certainly. In the video, a person is seen on the floor speaking to the camera. He then proceeds to mix various ingredients and lay plaster on the floor. Next, he takes measurements, cuts out a piece of tile, and continues laying tiles on the floor while maintaining eye contact with the camera."
},
{
"from": "human",
"value": "Can you pinpoint when the man starts laying the tiles on the floor?"
},
{
"from": "gpt",
"value": "The man begins laying tiles on the floor from <s1> to <e1>."
},
{
"from": "human",
"value": "What occurs between <s2> and <e2>?"
},
{
"from": "gpt",
"value": "During the interval from <s2> to <e2>, the man takes measurements, cuts out a piece of tile, and lays the tile on the floor."
}
],
"meta": {
"duration": 214.6,
"token": {
"<s0>": 0,
"<e0>": 40.8,
"<s1>": 41.9,
"<e1>": 119.1,
"<s2>": 96.6,
"<e2>": 170.6,
"<s3>": 168.5,
"<e3>": 214.6
}
},
"source": "anet"
},
{
"id": "v_oP77DgsbhKQ",
"conversations": [
{
"from": "human",
"value": "<video>\nPlease provide a summary of the video."
},
{
"from": "gpt",
"value": "In the video, a man is seen on his knees speaking to the camera. He then proceeds to mix various ingredients and lay plaster on the floor. After measuring the floor and tiles, the man cuts out a piece of tile and lays it on the floor. Throughout this process, the man occasionally looks back at the camera."
},
{
"from": "human",
"value": "Can you specify the time when the man begins laying plaster on the floor?"
},
{
"from": "gpt",
"value": "The man begins laying plaster on the floor from <s1> to <e1>."
},
{
"from": "human",
"value": "What occurs between <s2> and <e2>?"
},
{
"from": "gpt",
"value": "During the interval from <s2> to <e2>, the man measures the floor and tiles and prepares to cut out a piece of tile."
}
],
"meta": {
"duration": 214.6,
"token": {
"<s0>": 0,
"<e0>": 40.8,
"<s1>": 41.9,
"<e1>": 119.1,
"<s2>": 96.6,
"<e2>": 170.6,
"<s3>": 168.5,
"<e3>": 214.6
}
},
"source": "anet"
},
{
"id": "v_fzp5ooc727c",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you provide a brief description of the events in the video?"
},
{
"from": "gpt",
"value": "Certainly. The video begins with two lines of young men walking side by side along a road. One of them eventually stands in a field, where he engages in various activities: twisting a wooden object, bending down to pick up a ball, and playing baseball with the ball. Later on, a group of men is shown playing a game, and one of them attempts a penalty shot. Towards the end, everyone is depicted lying down on the ground, and a person starts to sit up but gets hit in the head by the ball, ultimately lying back down. The video concludes with the screen flashing to a black screen and the words \"The End\" appearing."
},
{
"from": "human",
"value": "Could you pinpoint when the man picked up the ball and began playing baseball?"
},
{
"from": "gpt",
"value": "Certainly. The man picks up the ball from <s2> to <e2> and proceeds to engage in a game of baseball."
},
{
"from": "human",
"value": "What happens to the ball after the man hits it?"
},
{
"from": "gpt",
"value": "The ball is thrown back by an unseen individual after the man hits it, as shown from <s4> to <e4>."
},
{
"from": "human",
"value": "Could you elaborate on the scene where everyone is depicted lying down on the ground?"
},
{
"from": "gpt",
"value": "Absolutely. The scene shows a group of people lying on the ground as if they are dead. One person begins to sit up, but they get hit in the head by the ball, causing them to lie back down. This sequence occurs from <s7> to <e7>."
}
],
"meta": {
"duration": 148.3,
"token": {
"<s0>": 0,
"<e0>": 14.8,
"<s1>": 15.6,
"<e1>": 32.6,
"<s2>": 32.6,
"<e2>": 44.5,
"<s3>": 44.5,
"<e3>": 65.3,
"<s4>": 66.7,
"<e4>": 72.7,
"<s5>": 74.2,
"<e5>": 107.5,
"<s6>": 106.0,
"<e6>": 130.5,
"<s7>": 129.8,
"<e7>": 137.9,
"<s8>": 137.9,
"<e8>": 148.3
}
},
"source": "anet"
},
{
"id": "v_fzp5ooc727c",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you provide a summary of the events in the video?"
},
{
"from": "gpt",
"value": "Of course! The video features a group of young men walking down a road together. One of them stops and stands in a field, where he twists a wooden object. He then bends down to grab a ball and plays baseball with it. Later, a larger group of men is shown playing a game together, and one player attempts a penalty shot. One person is seen lying down on the ground, followed by the screen flashing to black and displaying the text \"The End.\""
},
{
"from": "human",
"value": "Could you mark the exact moment when the man starts twisting the wooden object?"
},
{
"from": "gpt",
"value": "The man starts twisting the wooden object from <s1> to <e1>."
}
],
"meta": {
"duration": 148.3,
"token": {
"<s0>": 0,
"<e0>": 14.8,
"<s1>": 15.6,
"<e1>": 32.6,
"<s2>": 32.6,
"<e2>": 44.5,
"<s3>": 44.5,
"<e3>": 65.3,
"<s4>": 66.7,
"<e4>": 72.7,
"<s5>": 74.2,
"<e5>": 107.5,
"<s6>": 106.0,
"<e6>": 130.5,
"<s7>": 129.8,
"<e7>": 137.9,
"<s8>": 137.9,
"<e8>": 148.3
}
},
"source": "anet"
},
{
"id": "v_LNKdVrX_0Fg",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the primary action performed by the woman in the video?"
},
{
"from": "gpt",
"value": "The primary action performed by the woman in the video is demonstrating how to wrap a toy in wrapping paper, as she showcases the steps from <s1> to <e1>."
},
{
"from": "human",
"value": "Can you identify when the demonstration of wrapping the toy takes place?"
},
{
"from": "gpt",
"value": "Certainly. The demonstration of wrapping the toy occurs from <s1> to <e1>."
},
{
"from": "human",
"value": "What happens after the toy is wrapped in the wrapping paper?"
},
{
"from": "gpt",
"value": "After wrapping the toy in the wrapping paper, the woman proceeds to tape it up, which takes place from <s2> to <e2>."
}
],
"meta": {
"duration": 226.7,
"token": {
"<s0>": 0,
"<e0>": 22.7,
"<s1>": 22.7,
"<e1>": 179.1,
"<s2>": 182.5,
"<e2>": 226.7
}
},
"source": "anet"
},
{
"id": "v_LNKdVrX_0Fg",
"conversations": [
{
"from": "human",
"value": "<video>\nIn the video, what is the woman wearing and what is she doing?"
},
{
"from": "gpt",
"value": "The woman is wearing overalls and is engaged in the process of wrapping a toy in wrapping paper. She demonstrates her skills from <s1> to <e1> by meticulously laying out the wrapping paper and showing how to wrap the toy. Subsequently, she successfully wraps the toy from <s2> to <e2> and affixes it with tape."
},
{
"from": "human",
"value": "Can you identify when the woman starts to wrap the toy in the wrapping paper?"
},
{
"from": "gpt",
"value": "Certainly. The woman starts wrapping the toy from <s2> to <e2>."
}
],
"meta": {
"duration": 226.7,
"token": {
"<s0>": 0,
"<e0>": 22.7,
"<s1>": 22.7,
"<e1>": 179.1,
"<s2>": 182.5,
"<e2>": 226.7
}
},
"source": "anet"
},
{
"id": "v_XD3yFrJHiv8",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the primary focus of the woman in the video during the first occurrence, from <s0> to <e0>?"
},
{
"from": "gpt",
"value": "During the first occurrence, the woman's primary focus is to smooth out the papers on her clipboard while maintaining a pleasant smile. She also crosses her legs and sits back, indicating a sense of calm and contentment."
},
{
"from": "human",
"value": "Could you identify the source of the various clips that appear during the second occurrence, from <s1> to <e1>?"
},
{
"from": "gpt",
"value": "Certainly. The clips appear to be a mix of footage from a city, showcasing men playing soccer on sand in the middle of the city. Occasionally, blue words on the screen correspond to specific plays in the game."
},
{
"from": "human",
"value": "What occurs during the third occurrence, from <s2> to <e2>?"
},
{
"from": "gpt",
"value": "During the third occurrence, the man and woman engage in conversation after the clips end. The woman places her clipboard on the floor and joins the discussion."
}
],
"meta": {
"duration": 157.3,
"token": {
"<s0>": 0,
"<e0>": 16.5,
"<s1>": 29.9,
"<e1>": 152.6,
"<s2>": 152.6,
"<e2>": 157.3
}
},
"source": "anet"
},
{
"id": "v_XD3yFrJHiv8",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you summarize the video's content?"
},
{
"from": "gpt",
"value": "In the video, a woman sits on a couch, smiling and crossing her legs. She picks up a clipboard and appears to smooth out papers. As the clipboard footage transitions, various clips play, showing parts of a city and men playing soccer in the middle of it. The clips then come to an end, and the woman and the man resume their conversation. The woman puts her clipboard down during this time."
},
{
"from": "human",
"value": "Can you identify when the woman puts her clipboard down during the conversation?"
},
{
"from": "gpt",
"value": "Yes. The woman places her clipboard down from <s2> to <e2>."
}
],
"meta": {
"duration": 157.3,
"token": {
"<s0>": 0,
"<e0>": 16.5,
"<s1>": 29.9,
"<e1>": 152.6,
"<s2>": 152.6,
"<e2>": 157.3
}
},
"source": "anet"
},
{
"id": "v_lZKrd84QElk",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat is the primary activity taking place in the video?"
},
{
"from": "gpt",
"value": "The video primarily depicts a former president walking in a large field, accompanied by a woman and surrounded by a large crowd."
},
{
"from": "human",
"value": "Can you pinpoint when the president delivers a speech and greets people?"
},
{
"from": "gpt",
"value": "Certainly. The speech taking place from <s1> to <e1> is followed by the president greeting others and exchanging handshakes."
},
{
"from": "human",
"value": "What transpires during the time interval from <s2> to <e2>?"
},
{
"from": "gpt",
"value": "During that time, the former president is shown sharing a beer with other individuals in the crowd."
}
],
"meta": {
"duration": 65.8,
"token": {
"<s0>": 0.7,
"<e0>": 18.8,
"<s1>": 16.8,
"<e1>": 56.9,
"<s2>": 45.8,
"<e2>": 65.2
}
},
"source": "anet"
},
{
"id": "v_lZKrd84QElk",
"conversations": [
{
"from": "human",
"value": "<video>\nCan you give a concise overview of what's happening in the video?"
},
{
"from": "gpt",
"value": "In the video, the former president is seen engaging with a large crowd in a field. He delivers a speech, which elicits cheers from the audience. Afterward, he shakes hands and shares a beer with those around him."
},
{
"from": "human",
"value": "What is the context of the former president sharing a beer?"
},
{
"from": "gpt",
"value": "The context of the former president sharing a beer is during a casual, post-speech gathering with his supporters, fostering a sense of camaraderie and connection."
},
{
"from": "human",
"value": "Can you time-stamp the part where the former president gives his speech?"
},
{
"from": "gpt",
"value": "The former president's speech occurs from <s1> to <e1>."
},
{
"from": "human",
"value": "Are there any notable interactions between the former president and the woman in the video?"
},
{
"from": "gpt",
"value": "From <s0> to <e0>, the former president can be seen walking alongside a woman in the large field. However, there isn't any significant interaction between them during the video."
}
],
"meta": {
"duration": 65.8,
"token": {
"<s0>": 0.7,
"<e0>": 18.8,
"<s1>": 16.8,
"<e1>": 56.9,
"<s2>": 45.8,
"<e2>": 65.2
}
},
"source": "anet"
},
{
"id": "v_6lYTHj9vImo",
"conversations": [
{
"from": "human",
"value": "<video>\nWhat can you tell me about the video's content?"
},
{
"from": "gpt",
"value": "In the video, four kids are playing outside on the beach. The two girls on the right side of the screen have constructed sand castles and formed a large circle with water surrounding it. The boys, on the left side, seem to be observing this creative work."
},
{
"from": "human",
"value": "Could you pinpoint when the kids go from building sandcastles to fetching water?"
},
{
"from": "gpt",
"value": "Certainly. The transition from constructing sandcastles to fetching water occurs from <s1> to <e1>."
},
{
"from": "human",
"value": "What happens after the boy takes a look at the sandcastles and the water circle?"
},
{
"from": "gpt",
"value": "Following the boy's observation, the girls take off running towards the beach to collect more water. This event takes place from <s2> to <e2>."
}
],
"meta": {
"duration": 60.1,
"token": {
"<s0>": 0,
"<e0>": 15.3,
"<s1>": 15.9,
"<e1>": 34.3,
"<s2>": 34.6,
"<e2>": 49.6,
"<s3>": 49,
"<e3>": 60.1
}
},
"source": "anet"
},
{
"id": "v_6lYTHj9vImo",
"conversations": [
{
"from": "human",
"value": "<video>\nCould you provide a summary of the video's content?"
},
{
"from": "gpt",
"value": "The video features four kids playing in the sand at the beach. Two boys and two girls are shown, with the girls constructing sand castles and a large circle of water surrounding them. The kids run to the beach and bring back more water, with the boys observing their progress. Later, both girls return to the water to retrieve their floats, stopping mid-way."
},
{
"from": "human",
"value": "Could you pinpoint the specific moment when the girls start building sand castles and the circle of water?"
},
{
"from": "gpt",
"value": "The girls start building sand castles from <s1> to <e1>. The circular area filled with water surrounding it is also part of this event sequence."
},
{
"from": "human",
"value": "After the girls take off running for more water, do they return to the sandcastles they've built?"
},
{
"from": "gpt",
"value": "No, after taking off running for more water, the girls do not return to the sandcastles they've built. They instead head back to the water to grab their floats."
},
{
"from": "human",
"value": "Can you describe the boys' interaction with the girls' sandcastle creation?"
},
{
"from": "gpt",
"value": "During the timeframe from <s2> to <e2>, the boy observes the girls building the sandcastles and the circle of water surrounding them. However, he does not engage with the sandcastle construction or participate in the activity himself."
}
],
"meta": {
"duration": 60.1,
"token": {
"<s0>": 0,
"<e0>": 15.3,
"<s1>": 15.9,
"<e1>": 34.3,
"<s2>": 34.6,
"<e2>": 49.6,
"<s3>": 49,
"<e3>": 60.1
}
},
"source": "anet"
}
]
\ No newline at end of file
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
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