模型简介
模型特点
模型能力
使用案例
🚀 LLaVA-NeXT-Video模型卡
LLaVA-NeXT-Video是一个基于多模态数据微调的开源聊天机器人模型,能够处理视频和图像数据,在视频理解任务上表现出色。它基于lmsys/vicuna-7b-v1.5
进行微调,在VideoMME基准测试中达到了当前开源模型的最优性能。
点击下面的链接,在免费的Google Colab实例上运行LLaVA:
免责声明:发布LLaVA-NeXT-Video的团队并未为该模型编写模型卡,此模型卡由Hugging Face团队编写。
🚀 快速开始
模型使用步骤
首先,确保安装了 transformers >= 4.42.0
。该模型支持多视觉和多提示生成,即在提示中可以传递多个图像或视频。同时,请遵循正确的提示模板 (USER: xxx\nASSISTANT:
),并在需要查询图像或视频的位置添加 <image>
或 <video>
标记。
以下是在GPU设备上以 float16
精度运行生成的示例脚本:
import av
import torch
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import LlavaNextVideoProcessor, LlavaNextVideoForConditionalGeneration
model_id = "llava-hf/LLaVA-NeXT-Video-7B-hf"
model = LlavaNextVideoForConditionalGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
low_cpu_mem_usage=True,
).to(0)
processor = LlavaNextVideoProcessor.from_pretrained(model_id)
def read_video_pyav(container, indices):
'''
Decode the video with PyAV decoder.
Args:
container (`av.container.input.InputContainer`): PyAV container.
indices (`List[int]`): List of frame indices to decode.
Returns:
result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
'''
frames = []
container.seek(0)
start_index = indices[0]
end_index = indices[-1]
for i, frame in enumerate(container.decode(video=0)):
if i > end_index:
break
if i >= start_index and i in indices:
frames.append(frame)
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
# define a chat history and use `apply_chat_template` to get correctly formatted prompt
# Each value in "content" has to be a list of dicts with types ("text", "image", "video")
conversation = [
{
"role": "user",
"content": [
{"type": "text", "text": "Why is this video funny?"},
{"type": "video"},
],
},
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
container = av.open(video_path)
# sample uniformly 8 frames from the video, can sample more for longer videos
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
clip = read_video_pyav(container, indices)
inputs_video = processor(text=prompt, videos=clip, padding=True, return_tensors="pt").to(model.device)
output = model.generate(**inputs_video, max_new_tokens=100, do_sample=False)
print(processor.decode(output[0][2:], skip_special_tokens=True))
从 transformers>=v4.48
版本开始,你还可以将图像或视频的URL或本地路径传递给对话历史,让聊天模板处理后续操作。对于视频,还需要指定要从视频中采样的帧数 num_frames
,否则将加载整个视频。聊天模板会为你加载图像或视频,并返回 torch.Tensor
格式的输入,你可以直接将其传递给 model.generate()
。
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}
{"type": "video", "path": "my_video.mp4"},
{"type": "text", "text": "What is shown in this image and video?"},
],
},
]
inputs = processor.apply_chat_template(messages, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors"pt")
output = model.generate(**inputs, max_new_tokens=50)
以图像为输入进行推理
在按照上述步骤加载模型后,使用以下代码以图像为输入进行生成:
import requests
from PIL import Image
conversation = [
{
"role": "user",
"content": [
{"type": "text", "text": "What are these?"},
{"type": "image"},
],
},
]
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
image_file = "http://images.cocodataset.org/val2017/000000039769.jpg"
raw_image = Image.open(requests.get(image_file, stream=True).raw)
inputs_image = processor(text=prompt, images=raw_image, return_tensors='pt').to(0, torch.float16)
output = model.generate(**inputs_video, max_new_tokens=100, do_sample=False)
print(processor.decode(output[0][2:], skip_special_tokens=True))
以图像和视频为输入进行推理
在加载模型后,使用以下代码以图像和视频为输入进行生成:
conversation_1 = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's the content of the image>"},
{"type": "image"},
],
}
]
conversation_2 = [
{
"role": "user",
"content": [
{"type": "text", "text": "Why is this video funny?"},
{"type": "video"},
],
},
]
prompt_1 = processor.apply_chat_template(conversation_1, add_generation_prompt=True)
prompt_2 = processor.apply_chat_template(conversation_2, add_generation_prompt=True)
s = processor(text=[prompt_1, prompt_2], images=image, videos=clip, padding=True, return_tensors="pt").to(model.device)
# Generate
generate_ids = model.generate(**inputs, max_new_tokens=100)
out = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
print(out)
模型优化
通过bitsandbytes
库进行4位量化
首先,确保安装了 bitsandbytes
,使用 pip install bitsandbytes
进行安装,并确保可以访问支持CUDA的GPU设备。只需将上述代码片段修改如下:
model = LlavaNextVideoForConditionalGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
low_cpu_mem_usage=True,
+ load_in_4bit=True
)
使用Flash-Attention 2进一步加速生成
首先,确保安装了 flash-attn
。有关该包的安装,请参考 Flash Attention的原始仓库。只需将上述代码片段修改如下:
model = LlavaNextVideoForConditionalGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
low_cpu_mem_usage=True,
+ use_flash_attention_2=True
).to(0)
✨ 主要特性
- 多模态处理:支持处理图像和视频数据,能够在提示中传递多个图像或视频。
- 高性能:在VideoMME基准测试中达到了当前开源模型的最优性能。
- 灵活的输入方式:从
transformers>=v4.48
版本开始,支持传递图像或视频的URL或本地路径。 - 模型优化:支持4位量化和Flash-Attention 2,可加速模型推理。
📦 安装指南
确保安装 transformers >= 4.42.0
,如果需要进行模型优化,还需要安装 bitsandbytes
和 flash-attn
。
pip install transformers>=4.42.0
pip install bitsandbytes # 用于4位量化
# 参考 https://github.com/Dao-AILab/flash-attention 安装 flash-attn
📚 详细文档
📄 模型详情
属性 | 详情 |
---|---|
模型类型 | LLaVA-Next-Video是一个基于多模态指令跟随数据微调大语言模型(LLM)得到的开源聊天机器人。该模型在LLaVa-NeXT的基础上,通过在视频和图像数据的混合数据集上进行微调,以实现更好的视频理解能力。视频数据均匀采样为每个片段32帧。该模型在VideoMME基准测试中达到了当前开源模型的最优性能。基础大语言模型为lmsys/vicuna-7b-v1.5。 |
模型日期 | LLaVA-Next-Video-7B于2024年4月进行训练。 |
更多信息的论文或资源 | https://github.com/LLaVA-VL/LLaVA-NeXT |
📚 训练数据集
图像
- 从LAION/CC/SBU中筛选出的558K图像-文本对,由BLIP添加标题。
- 158K由GPT生成的多模态指令跟随数据。
- 500K面向学术任务的VQA混合数据。
- 50K GPT-4V混合数据。
- 40K ShareGPT数据。
视频
- 100K VideoChatGPT-Instruct数据。
📊 评估数据集
包含4个基准测试的集合,其中包括3个学术VQA基准测试和1个字幕生成基准测试。
🔧 技术细节
LLaVA-Next-Video基于lmsys/vicuna-7b-v1.5
进行微调,通过在多模态数据上的训练,提升了模型的视频理解能力。模型在训练过程中,对视频数据进行均匀采样,每个视频片段采样32帧。在推理过程中,可以通过指定采样帧数来处理不同长度的视频。同时,模型支持多视觉和多提示生成,能够在提示中传递多个图像或视频。
📄 许可证
Llama 2遵循LLAMA 2社区许可证,版权归Meta Platforms, Inc.所有。
✏️ 引用
如果您在研究中使用了我们的论文和代码,请引用以下文献:
@misc{zhang2024llavanextvideo,
title={LLaVA-NeXT: A Strong Zero-shot Video Understanding Model},
url={https://llava-vl.github.io/blog/2024-04-30-llava-next-video/},
author={Zhang, Yuanhan and Li, Bo and Liu, haotian and Lee, Yong jae and Gui, Liangke and Fu, Di and Feng, Jiashi and Liu, Ziwei and Li, Chunyuan},
month={April},
year={2024}
}
@misc{liu2024llavanext,
title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
month={January},
year={2024}
}



