Transformers documentation

视频文本到文本

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

视频文本到文本

视频文本到文本模型,也称为视频语言模型,能够处理视频并输出文本。这类模型可以应对多种任务,从视频问答到视频字幕生成。

这些模型的架构与图文到文本模型几乎相同,只是做了一些修改以接受视频数据,因为视频数据本质上就是具有时间依赖性的图像帧。一些图文到文本模型可以接受多张图像,但仅凭这一点还不足以让模型接受视频。

此外,视频-文本到文本模型通常使用所有视觉模态进行训练。每个示例可能包含视频、多个视频、图像以及多张图像。其中一些模型还可以接受交错输入。例如,你可以在文本字符串中通过添加视频标记来引用特定的视频,例如“这个视频中发生了什么?<video>”。

请注意,这些模型处理的是不含音频的视频。而 Any-to-any 模型则可以处理包含音频的视频。

在本指南中,我们将简要介绍视频语言模型,并展示如何使用 Transformers 进行推理。

首先,视频 LM 有多种类型:

  • 用于微调的基础模型
  • 用于对话的经过微调的聊天模型
  • 经过指令微调的模型

本指南专注于使用经过指令微调的模型进行推理,llava-hf/llava-onevision-qwen2-0.5b-ov-hf 可以接受交错数据。或者,如果你的硬件无法运行 7B 模型,可以尝试 llava-interleave-qwen-0.5b-hf。

让我们开始安装依赖项。

pip install -q transformers accelerate flash_attn torchcodec

让我们初始化模型和处理器。

from transformers import AutoProcessor, LlavaOnevisionForConditionalGeneration
import torch
model_id = "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"

device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
processor = AutoProcessor.from_pretrained(model_id, device=device)

model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map="auto", dtype=torch.float16)

我们将使用两个视频进行推理,这两个视频中都包含猫。

视频是一系列图像帧。根据硬件限制,需要进行降采样。如果降采样后的帧数过少,预测质量将会较低。

视频-文本到文本模型的处理器中抽象了视频处理器。您可以将视频推理相关的参数传递给 apply_chat_template() 函数。

您可以在此处了解更多关于视频处理器的信息:这里。

我们可以定义聊天历史记录,并传入如下所示的带有 URL 的视频。

messages = [
    {
        "role": "user",
        "content": [
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4"},
            {"type": "text", "text": "Describe what is happening in this video."},
        ],
    }
]

你可以通过传入 messages、将 do_sample_frames 设置为 True 并传入 num_frames 来对视频进行预处理。这里我们采样了 10 帧。

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    num_frames=10,
    do_sample_frames=True
)
inputs.to(model.device)

输入包含用于分词文本的 input_ids、用于 10 帧的 pixel_values_videos 以及用于标记哪些 token 的 attention_mask。

现在,我们可以使用预处理后的输入进行推理并解码结果。

generated_ids = model.generate(**inputs, max_new_tokens=128)
input_length = len(inputs["input_ids"][0])
output_text = processor.batch_decode(
    generated_ids[:, input_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False
)
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text[0])

#"The video features a fluffy, long-haired cat with a mix of brown and white fur, lying on a beige carpeted floor. The cat's eyes are wide open, and its whiskers are prominently visible. The cat appears to be in a relaxed state, with its head slightly"

您也可以在聊天模板中直接交错插入多个视频和文本,如下所示。

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Here's a video."},
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4"},
            {"type": "text", "text": "Here's another video."},
            {"type": "video", "video": "https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_2.mp4"},
            {"type": "text", "text": "Describe similarities in these videos."},
        ],
    }
]

推理过程与上一个示例相同。

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_dict=True,
    return_tensors="pt",
    num_frames=100,
    do_sample_frames=True
)
inputs.to(model.device)

generated_ids = model.generate(**inputs, max_new_tokens=50)
input_length = len(inputs["input_ids"][0])
output_text = processor.batch_decode(
    generated_ids[:, input_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
#['Both videos feature a cat with a similar appearance, characterized by a fluffy white coat with black markings, a pink nose, and a pink tongue. The cat\'s eyes are wide open, and it appears to be in a state of alertness or excitement. ']
Update on GitHub