模型简介
模型特点
模型能力
使用案例
语言:
- 英文 许可证: llama2 任务标签: 视频文本转文本 数据集:
- lmms-lab/VideoChatGPT
LLaVA-NeXT-Video 模型卡片
也可查看Google Colab演示,在免费层级的Google Colab实例上运行Llava:
免责声明:发布LLaVa-NeXT-Video的团队未为此模型编写模型卡片,因此本模型卡片由Hugging Face团队编写。
📄 模型详情
模型类型: LLaVA-Next-Video是一个开源聊天机器人,通过在多模态指令跟随数据上微调LLM训练而成。该模型基于LLaVa-NeXT构建,通过在视频和图像数据的混合上进行调优,以实现更好的视频理解能力。视频采样均匀,每段剪辑包含32帧。 该模型目前在VideoMME基准上是开源模型中的SOTA。 基础LLM: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个字幕基准。
🚀 如何使用模型
首先,确保安装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):
'''
使用PyAV解码器解码视频。
参数:
container (`av.container.input.InputContainer`): PyAV容器。
indices (`List[int]`): 要解码的帧索引列表。
返回:
result (np.ndarray): 解码帧的np数组,形状为(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])
# 定义聊天历史并使用`apply_chat_template`获取正确格式的提示
# "content"中的每个值必须是包含类型("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)
# 从视频中均匀采样8帧,对于更长的视频可以采样更多帧
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_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)
🔒 许可证
Llama 2根据LLAMA 2社区许可证授权, 版权所有 (c) 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}
}



