# Video-LLaVA

## 概述

Video-LLaVa 是一个开源的多模态 LLM，通过在 Llava1.5 和 VideChat 生成的多模态指令跟随数据上对 LlamA/Vicuna 进行微调而训练得到。它是一个基于 transformer 架构的自回归语言模型。Video-LLaVa 将视觉表示统一到语言特征空间，使 LLM 能够同时对图像和视频执行视觉推理。

Video-LLaVA 模型由 Bin Lin、Yang Ye、Bin Zhu、Jiaxi Cui、Munang Ning、Peng Jin 和 Li Yuan 在 [Video-LLaVA: Learning United Visual Representation by Alignment Before Projection](https://huggingface.co/papers/2311.10122) 中提出。

该论文的摘要如下：

*大型视觉-语言模型（LVLM）提升了视觉-语言理解中多种下游任务的性能。大多数现有方法将图像和视频编码到各自独立的特征空间中，然后将其作为输入提供给大型语言模型。然而，由于图像和视频缺乏统一的标记化（即投影前的不对齐），大型语言模型（LLM）很难从几个质量较差的投影层中学习多模态交互。在本工作中，我们将视觉表示统一到语言特征空间中，以推动基础 LLM 向统一的 LVLM 发展。因此，我们建立了一个简单但稳健的 LVLM 基线，Video-LLaVA，它从图像和视频的混合数据集中学习，使两者相互增强。Video-LLaVA 在涵盖 5 个图像问答数据集和 4 个图像基准工具包的 9 个图像基准上取得了卓越的性能。此外，我们的 Video-LLaVA 在 MSRVTT、MSVD、TGIF 和 ActivityNet 上分别比 Video-ChatGPT 高出 5.8%、9.9%、18.6% 和 10.1%。值得注意的是，大量实验表明，Video-LLaVA 在统一的视觉表示中使图像和视频相互受益，其性能优于专为图像或视频设计的模型。我们希望这项工作能为 LLM 的多模态输入提供一些有益的见解*

## 使用技巧

- 我们建议用户在计算批量生成时使用 padding_side="left"，因为这会带来更准确的结果。只需确保在生成之前调用 processor.tokenizer.padding_side = "left" 即可。

- 请注意，该模型并未被明确训练以在同一提示中处理多张图像/视频，尽管这在技术上是可行的，但您可能会遇到不准确的结果。

- 请注意，视频输入在输入时应当恰好包含 8 帧，因为模型是在该设置下训练的。

该模型由 [RaushanTurganbay](https://huggingface.co/RaushanTurganbay) 贡献。原始代码可在[此处](https://github.com/PKU-YuanGroup/Video-LLaVA)找到。

> [!NOTE]
> 在 v4.46 版本发布后，LLaVA 模型将针对添加 `processor.patch_size = {{patch_size}}`、`processor.num_additional_image_tokens = {{num_additional_image_tokens}}` 和 `processor.vision_feature_select_strategy = {{vision_feature_select_strategy}}` 发出警告。如果您拥有该模型检查点，强烈建议将这些属性添加到处理器中；如果该检查点不属于您，则建议提交一个 PR。
添加这些属性后，LLaVA 将尝试推断每张图像所需的图像 token 数量，并在文本中扩展相应数量的 `<image>` 占位符。通常每张图像约为 500 个 token，因此请确保文本未被截断，否则在合并嵌入时将会失败。这些属性可以从模型配置中获取，例如 `model.config.vision_config.patch_size` 或 `model.config.vision_feature_select_strategy`。如果视觉骨干网络添加了 CLS token，则 `num_additional_image_tokens` 应为 `1`；如果未向视觉 patch 添加任何额外内容，则应为 `0`。

## 使用示例

### 单一媒体模式

该模型可以接受图像和视频作为输入。以下是在半精度（`torch.float16`）下进行推理的示例代码：

```python
import av
import numpy as np

from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor

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])

# Load the model in half-precision
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", device_map="auto")
processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")

# Load the video as an np.array, sampling uniformly 8 frames
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)
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
video = read_video_pyav(container, indices)

# For better results, we recommend to prompt the model in the following format
prompt = "USER: <video>\nWhy is this funny? ASSISTANT:"
inputs = processor(text=prompt, videos=video, return_tensors="pt").to(model.device)

out = model.generate(**inputs, max_new_tokens=60)
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)
```

对于多轮对话，请将提示格式更改为：

```bash
"USER: <video>\nWhat do you see in this video? ASSISTANT: A baby reading a book. USER: Why is the it funny? ASSISTANT:"
```

### 混合媒体模式

该模型还可以从交错的图像-视频输入中生成内容。但请注意，它并非在交错的图像-视频设置下训练的，这可能会影响性能。以下是混合媒体输入的使用示例，请在上述代码片段中添加以下行：

```python
import requests
from PIL import Image

# Generate from image and video mixed inputs
# Load and image and write a new prompt
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
prompt = "USER: <image>\nHow many cats are there in the image? ASSISTANT: There are two cats. USER: <video>\nWhy is this video funny? ASSISTANT:"

inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt").to(model.device)

# Generate
generate_ids = model.generate(**inputs, max_length=50)
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
```

## 模型优化

### 使用 Bitsandbytes 进行量化以实现内存效率

模型可以以更低的位宽加载，在保持原始模型性能的同时显著降低内存占用，从而实现在资源受限场景下的高效部署。

首先，请通过运行 `pip install bitsandbytes` 安装 bitsandbytes，并确保您拥有该库支持的 GPU/加速器。

bitsandbytes 正在重构以支持 CUDA 之外的多种后端。目前，ROCm（AMD GPU）和 Intel CPU 的实现已趋于成熟，Intel XPU 正在开发中，预计将在第四季度/第一季度支持 Apple Silicon。有关安装说明和最新的后端更新，请访问 [此链接](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend)。

我们非常重视您的反馈，以便在正式发布前发现并修复问题！请查阅[这些文档](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends)以获取更多详情和反馈链接。

只需按照下图所示添加 [BitsAndBytesConfig](/docs/transformers/main/zh/main_classes/quantization#transformers.BitsAndBytesConfig)，即可加载量化模型：

```python
from transformers import BitsAndBytesConfig, VideoLlavaForConditionalGeneration

# specify how to quantize the model
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.float16,
)

model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", quantization_config=quantization_config, device_map="auto")
```

### 使用 Flash-Attention 2 加速生成

此外，通过使用 [Flash Attention](../kernel_doc/loading_kernels#attention-kernels)，我们可以大幅加快模型推理速度。Flash Attention 是模型内部所用注意力机制的一种更快实现。

首先，请确保安装最新版本的 Flash Attention 2：

```bash
pip install -U flash-attn --no-build-isolation
```

此外，您的硬件必须与 Flash-Attention 2 兼容。有关详细信息，请参阅 [flash attention 仓库](https://github.com/Dao-AILab/flash-attention) 的官方文档。只有当模型以 `torch.float16` 或 `torch.bfloat16` 加载时，才能使用 FlashAttention-2。

要使用 Flash Attention-2 加载并运行模型，只需在加载模型时添加 `attn_implementation="flash_attention_2"`，如下所示：

```python
from transformers import VideoLlavaForConditionalGeneration

model = VideoLlavaForConditionalGeneration.from_pretrained(
    "LanguageBind/Video-LLaVA-7B-hf", , 
    attn_implementation="flash_attention_2",
).to(0, device_map="auto")
```

## VideoLlavaConfig[[transformers.VideoLlavaConfig]]

#### transformers.VideoLlavaConfig[[transformers.VideoLlavaConfig]]

```python
transformers.VideoLlavaConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, image_token_index: int = 32000, video_token_index: int = 32001, projector_hidden_act: str = 'gelu', vision_feature_select_strategy: typing.Literal['default', 'full'] = 'default', vision_feature_layer: int | list[int] = -2, image_seq_length: int = 256, video_seq_length: int = 2056, multimodal_projector_bias: bool = True, tie_word_embeddings: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/configuration_video_llava.py#L29)

**参数：**

vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：视觉骨干网络的配置对象或字典。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

image_token_index (`int`, *可选*, 默认为 `32000`) : 用作输入图像占位符的图像 token 索引。

video_token_index (`int`，*可选*，默认为 `32001`)：用作输入视频占位符的视频 token 索引。

projector_hidden_act (`str`，*可选*，默认为 `gelu`)：多模态投影器所使用的激活函数。

vision_feature_select_strategy (`Literal[default, full]`，*可选*，默认为 `default`)：用于从视觉骨干网络中选择视觉特征的特征选择策略。

vision_feature_layer (`Union[int, list[int]]`，*可选*，默认为 `-2`)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

image_seq_length (`int`, *可选*, 默认为 `256`) : 单个图像嵌入的序列长度。

video_seq_length (`int`, *可选*, 默认为 `2056`) : 单个视频嵌入的序列长度。

multimodal_projector_bias (`bool`，*可选*，默认为 `True`)：是否在多模态投影器中使用偏置。

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 VideoLlavaModel 配置的类。它根据指定的参数实例化 Video Llava 模型，并定义模型架构。使用默认值实例化配置将生成与 [LanguageBind/Video-LLaVA-7B-hf](https://huggingface.co/LanguageBind/Video-LLaVA-7B-hf) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import VideoLlavaForConditionalGeneration, VideoLlavaConfig, CLIPVisionConfig, LlamaConfig

>>> # Initializing a CLIP-vision config
>>> vision_config = CLIPVisionConfig()

>>> # Initializing a Llama config
>>> text_config = LlamaConfig()

>>> # Initializing a VideoLlava video_llava-1.5-7b style configuration
>>> configuration = VideoLlavaConfig(vision_config, text_config)

>>> # Initializing a model from the video_llava-1.5-7b style configuration
>>> model = VideoLlavaForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## VideoLlavaImageProcessor[[transformers.VideoLlavaImageProcessor]]

#### transformers.VideoLlavaImageProcessor[[transformers.VideoLlavaImageProcessor]]

```python
transformers.VideoLlavaImageProcessor(do_resize: bool = True, size: dict[str, int] | None = None, resample: Resampling = <Resampling.BICUBIC: 3>, do_center_crop: bool = True, crop_size: dict[str, int] | None = None, do_rescale: bool = True, rescale_factor: int | float = 0.00392156862745098, do_normalize: bool = True, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, do_convert_rgb: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/image_processing_video_llava.py#L58)

**参数：**

do_resize (`bool`，*可选*，默认为 `True`)：是否将图像的（高度，宽度）维度调整为指定的 `size`。可被 `preprocess` 方法中的 `do_resize` 覆盖。

size (`dict[str, int]` *可选*，默认为 `{"shortest_edge" : 224}`)：调整大小后图像的尺寸。图像的最短边会被调整为 size["shortest_edge"]，最长边则按比例调整以保持输入的宽高比。可以在 `preprocess` 方法中通过 `size` 进行覆盖。

resample (`PILImageResampling`，*可选*，默认为 `Resampling.BICUBIC`)：在调整图像大小时使用的重采样滤波器。可被 `preprocess` 方法中的 `resample` 覆盖。

do_center_crop (`bool`，*可选*，默认为 `True`)：是否将图像中心裁剪至指定的 `crop_size`。可通过 `preprocess` 方法中的 `do_center_crop` 进行覆盖。

crop_size (`dict[str, int]` *可选*，默认为 224) : 应用 `center_crop` 后输出图像的尺寸。可被 `preprocess` 方法中的 `crop_size` 覆盖。

do_rescale (`bool`，*可选*，默认为 `True`)：是否按指定的缩放因子 `rescale_factor` 对图像进行重新缩放。可在 `preprocess` 方法中通过 `do_rescale` 覆盖。

rescale_factor (`int` 或 `float`，*可选*，默认为 `1/255`) : 如果重新缩放图像，则使用的缩放因子。可被 `preprocess` 方法中的 `rescale_factor` 覆盖。

do_normalize (`bool`，*可选*，默认为 `True`)：是否对图像进行归一化。可通过 `preprocess` 方法中的 `do_normalize` 进行覆盖。

image_mean (`float` 或 `list[float]`，*可选*，默认为 `[0.48145466, 0.4578275, 0.40821073]`) : 对图像进行归一化时使用的均值。这是一个浮点数或浮点数列表，其长度等于图像的通道数。可以通过 `preprocess` 方法中的 `image_mean` 参数进行覆盖。

image_std (`float` 或 `list[float]`，*可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 归一化图像时使用的标准差。这是一个浮点数或浮点数列表，其长度等于图像的通道数。可被 `preprocess` 方法中的 `image_std` 参数覆盖。可被 `preprocess` 方法中的 `image_std` 参数覆盖。

do_convert_rgb (`bool`，*可选*，默认为 `True`)：是否将图像转换为 RGB。

构建一个 CLIP 图像处理器。

#### preprocess[[transformers.VideoLlavaImageProcessor.preprocess]]

```python
preprocess(images: list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]] | None = None, do_resize: bool | None = None, size: dict[str, int] | None = None, resample: PIL.Image.Resampling | None = None, do_center_crop: bool | None = None, crop_size: int | None = None, do_rescale: bool | None = None, rescale_factor: float | None = None, do_normalize: bool | None = None, image_mean: float | list[float] | None = None, image_std: float | list[float] | None = None, do_convert_rgb: bool | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = None, data_format: transformers.image_utils.ChannelDimension | None = <ChannelDimension.FIRST: 'channels_first'>, input_data_format: str | transformers.image_utils.ChannelDimension | None = None, return_legacy_image_output: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/image_processing_video_llava.py#L182)

**参数：**

images (`ImageInput`，*可选*)：待预处理的图像列表。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

do_resize (`bool`, *可选*, 默认为 `self.do_resize`) : 是否调整图像大小。

size (`dict[str, int]`，*可选*，默认为 `self.size`) : 调整大小后图像的尺寸。图像的最短边会被调整为 size["shortest_edge"]，最长边则按比例调整以保持输入的宽高比。

resample (`int`，*可选*，默认为 `self.resample`)：在对图像进行缩放时使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_center_crop (`bool`，*可选*，默认为 `self.do_center_crop`)：是否对图像进行中心裁剪。

crop_size (`dict[str, int]`，*可选*，默认为 `self.crop_size`)：中心裁剪的大小。仅当 `do_center_crop` 设置为 `True` 时生效。

do_rescale (`bool`, *可选*, 默认为 `self.do_rescale`) : 是否对图像进行重新缩放。

rescale_factor (`float`, *可选*, 默认为 `self.rescale_factor`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *可选*, 默认为 `self.do_normalize`) : 是否对图像进行归一化。

image_mean (`float` 或 `list[float]`，*可选*，默认为 `self.image_mean`)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`float` 或 `list[float]`，*可选*，默认为 `self.image_std`)：用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_convert_rgb (`bool`，*可选*，默认为 `self.do_convert_rgb`)：是否将图像转换为 RGB。

return_tensors (`str` 或 `TensorType`，*可选*) : 要返回的张量类型。可以是以下之一： - 未设置：返回 `np.ndarray` 列表。 - `TensorType.PYTORCH` 或 `'pt'`：返回类型为 `torch.Tensor` 的批次。 - `TensorType.NUMPY` 或 `'np'`：返回类型为 `np.ndarray` 的批次。

data_format (`ChannelDimension` 或 `str`，*可选*，默认为 `ChannelDimension.FIRST`)：输出图像的通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - 未设置：使用输入图像的通道维度格式。

input_data_format (`ChannelDimension` 或 `str`，*可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

预处理一张图像或一批图像。

## VideoLlavaVideoProcessor[[transformers.VideoLlavaVideoProcessor]]

#### transformers.VideoLlavaVideoProcessor[[transformers.VideoLlavaVideoProcessor]]

```python
transformers.VideoLlavaVideoProcessor(**kwargs: *<class 'transformers.processing_utils.VideosKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/video_processing_video_llava.py#L22)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 224}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 size 为整数时，是否在调整大小时默认使用正方形图像。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.48145466, 0.4578275, 0.40821073]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.26862954, 0.26130258, 0.27577711]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_center_crop (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行居中裁剪。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 224, 'width': 224}`)：应用 `center_crop` 后输出图像的尺寸。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

do_sample_frames (`bool`, *kwargs*, *可选*，默认为 `False`)：是否在处理前从视频中采样帧，还是处理整个视频。

video_metadata (`Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None]`, *kwargs*) : 视频的元数据，包含总时长、帧率（fps）和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频，否则请勿传入任何元数据。

fps (`Annotated[int | float | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，每秒采样的目标帧数。

num_frames (`Annotated[int | None, None]`, *kwargs*) : 当 `do_sample_frames=True` 时，要采样的最大帧数。

return_metadata (`bool`, *kwargs*, *可选*，默认为 `False`) : 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([VideosKwargs](/docs/transformers/main/zh/main_classes/processors#transformers.VideosKwargs), *optional*) : 每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

构建一个 VideoLlavaVideoProcessor 视频处理器。

## VideoLlavaProcessor[[transformers.VideoLlavaProcessor]]

#### transformers.VideoLlavaProcessor[[transformers.VideoLlavaProcessor]]

```python
transformers.VideoLlavaProcessor(image_processor = None, video_processor = None, tokenizer = None, patch_size = 14, vision_feature_select_strategy = 'default', image_token = '<image>', video_token = '<video>', chat_template = None, num_additional_image_tokens = 1, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/processing_video_llava.py#L27)

**参数：**

image_processor (`VideoLlavaImageProcessor`)：图像处理器是必需的输入。

video_processor (`VideoLlavaVideoProcessor`)：视频处理器是必需的输入。

tokenizer (`tokenizer_class`)：分词器是必需的输入。

patch_size (`int`，*可选*，默认为 14)：视觉塔的补丁大小。

vision_feature_select_strategy (`str`, *可选*, 默认为 `"default"`) : 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的设置保持一致

image_token (`str`，*可选*，默认为 `"<image>"`)：用于表示图像位置的专用标记。

video_token (`str`，*可选*，默认为 `"<video>"`)：用于表示视频位置的专用标记。

chat_template (`str`) : 一个 Jinja 模板，用于将聊天中的消息列表转换为可分词的字符串。

num_additional_image_tokens (`int`，*可选*，默认为 1)：添加到图像嵌入中的额外标记数量，例如 CLS（+1）。如果主干网络没有附加 CLS 或其他额外标记，则无需设置此参数。

构建一个 VideoLlavaProcessor，它将图像处理器、视频处理器和分词器封装为单一处理器。

[VideoLlavaProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaProcessor) 提供了 [VideoLlavaImageProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaImageProcessor)、[VideoLlavaVideoProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaVideoProcessor) 和 `tokenizer_class` 的所有功能。有关更多信息，请参阅 [~VideoLlavaImageProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaImageProcessor)、[~VideoLlavaVideoProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaVideoProcessor) 和 `~tokenizer_class`。

#### __调用__[[transformers.VideoLlavaProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py#L671)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要预处理的图像。期望输入单张图像或一批图像，其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`，*可选*)：要预处理的视频。期望输入单个视频或一批视频，其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间，请设置 `do_rescale=False`。

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`，*可选*)：要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。对于 NumPy 数组/PyTorch 张量，每个音频的形状应为 (C, T)，其中 C 是通道数，T 是音频的采样长度。

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

## VideoLlavaModel[[transformers.VideoLlavaModel]]

#### transformers.VideoLlavaModel[[transformers.VideoLlavaModel]]

```python
transformers.VideoLlavaModel(config: VideoLlavaConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L134)

**参数：**

config ([VideoLlavaConfig](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由视觉骨干网络和语言模型组成的 VideoLlava 模型，不包含语言建模头。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.VideoLlavaModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, vision_feature_layer: int | list[int] | None = None, vision_feature_select_strategy: str | None = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L268)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 `video_processor_class` 获取视频的像素值。有关详细信息，请参阅 `video_processor_class.__call__`（`processor_class` 使用 `video_processor_class` 来处理视频）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"` 之一。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `VideoLlavaModelOutputWithPast` 或 `tuple(torch.Tensor)`

`VideoLlavaModelOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[VideoLlavaModel](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.FloatTensor`）-- 语言模型主干最后一层输出的隐藏状态序列。如果使用 `cache`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列最后一个隐藏状态。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。

#### get_image_features[[transformers.VideoLlavaModel.get_image_features]]

```python
get_image_features(pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_images: typing.Optional[torch.Tensor] = None, vision_feature_layer: int | list[int] | None = None, vision_feature_select_strategy: str | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L145)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [VideoLlavaImageProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaImageProcessor) 获取像素值。有关详细信息，请参阅 [VideoLlavaImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[VideoLlavaProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaProcessor) 使用 [VideoLlavaImageProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaImageProcessor) 来处理图像）。

pixel_values_images (`torch.Tensor`，形状为 `(batch_size, channels, height, width)`)：与输入图像对应的张量。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"`

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"` 之一。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[VideoLlavaConfig](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaConfig)）和输入。

从视觉塔获取图像的最后隐藏状态，并应用多模态投影。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

#### get_placeholder_mask[[transformers.VideoLlavaModel.get_placeholder_mask]]

```python
get_placeholder_mask(input_ids: LongTensor, inputs_embeds: Tensor, image_features: typing.Optional[torch.Tensor] = None, video_features: typing.Optional[torch.Tensor] = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L225)

从 `input_ids` 或 `inputs_embeds` 中获取多模态占位符掩码，并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致，则会引发错误。

#### get_video_features[[transformers.VideoLlavaModel.get_video_features]]

```python
get_video_features(pixel_values_videos: Tensor, vision_feature_layer: int | list[int] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L191)

**参数：**

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`)：与输入视频对应的张量。可以使用 [VideoLlavaVideoProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaVideoProcessor) 获取视频的像素值。有关详细信息，请参阅 [VideoLlavaVideoProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2VideoProcessor.__call__)（[VideoLlavaProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaProcessor) 使用 [VideoLlavaVideoProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaVideoProcessor) 来处理视频）。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[VideoLlavaConfig](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaConfig)）和输入。

从视觉塔获取视频的最后隐藏状态，并应用多模态投影。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

## VideoLlavaForConditionalGeneration[[transformers.VideoLlavaForConditionalGeneration]]

#### transformers.VideoLlavaForConditionalGeneration[[transformers.VideoLlavaForConditionalGeneration]]

```python
transformers.VideoLlavaForConditionalGeneration(config: VideoLlavaConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L346)

**参数：**

config ([VideoLlavaConfig](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

由视觉骨干网络和语言模型组成的 VideoLlava 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.VideoLlavaForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, pixel_values_images: typing.Optional[torch.Tensor] = None, pixel_values_videos: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, vision_feature_layer: int | list[int] | None = None, vision_feature_select_strategy: str | None = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L382)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

pixel_values_images (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)) : The tensors corresponding to the input images. Pixel values can be obtained using [AutoImageProcessor](/docs/transformers/main/zh/model_doc/auto#transformers.AutoImageProcessor). See [VideoLlavaImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) for details ([]`LlavaProcessor`] uses [VideoLlavaImageProcessor](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaImageProcessor) for processing images).

pixel_values_videos (`torch.Tensor`，形状为 `(batch_size, num_frames, num_channels, frame_size, frame_size)`，*可选*)：与输入视频对应的张量。可以使用 `video_processor_class` 获取视频的像素值。有关详细信息，请参阅 `video_processor_class.__call__`（`processor_class` 使用 `video_processor_class` 来处理视频）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

cache (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常指模型在解码的先前阶段返回的 `cache`，此时 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `cache`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入格式相同的缓存。 如果使用 `cache`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"` 之一。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`, *可选*) : 如果设置为 `True`，则会返回 `cache` 键值状态，可用于加速解码（参见 `cache`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** `VideoLlavaCausalLMOutputWithPast` 或 `tuple(torch.Tensor)`

`VideoLlavaCausalLMOutputWithPast` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[VideoLlavaForConditionalGeneration](/docs/transformers/main/zh/model_doc/video_llava#transformers.VideoLlavaForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.FloatTensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.FloatTensor`）—— 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **cache** (`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。其中包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.FloatTensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.FloatTensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每个层的输出各一个），形状为 `(batch_size, sequence_length, hidden_size)`。语言模型主干在每个层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.FloatTensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.FloatTensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。语言模型主干的注意力权重，位于注意力 softmax 之后。
- **image_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 图像编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何图像，则为 `None`。
- **video_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 视频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理任何视频，则为 `None`。
- **audio_outputs**（`BaseModelOutputWithPooling`，*可选*）-- 音频编码器的输出：`last_hidden_state`、`pooler_output`、`hidden_states` 和 `attentions`。如果未处理音频，则为 `None`。

示例：

```python
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import numpy as np
>>> import av
>>> from huggingface_hub import hf_hub_download
>>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration

>>> 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])

>>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
>>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")

>>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
>>> 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
>>> 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 = processor(text=prompt, videos=clip, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=80)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER:  Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.Ъ. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a"

>>> # to generate from image and video mix
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> prompt = [
...     "USER: <image>\nHow many cats do you see? ASSISTANT:",
...     "USER: <video>\nWhy is this video funny? ASSISTANT:"
... ]
>>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=50)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
['USER:   How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER:  Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.Ъ. The baby is holding the remote']
```

#### get_image_features[[transformers.VideoLlavaForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, vision_feature_layer: int | list[int] | None = None, vision_feature_select_strategy: str | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/video_llava/modeling_video_llava.py#L359)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

vision_feature_layer (`Union[int, list[int]]`，*可选*)：用于选择视觉特征的层索引。如果提供了多个索引，则会将对应索引的视觉特征拼接起来，以形成视觉特征。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"`

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

