# LLaVa-NeXT-Video

## 概述

LLaVa-NeXT-Video 模型由 Yuanhan Zhang、Bo Li、Haotian Liu、Yong Jae Lee、Liangke Gui、Di Fu、Jiashi Feng、Ziwei Liu 和 Chunyuan Li 在 [LLaVA-NeXT: A Strong Zero-shot Video Understanding Model](https://llava-vl.github.io/blog/2024-04-30-llava-next-video/) 中提出。LLaVa-NeXT-Video 通过在视频和图像混合数据集上进行微调，改进了 [LLaVa-NeXT](llava_next)，从而提升了模型在视频上的性能。

[LLaVA-NeXT](llava_next) 在零样本（zero-shot）方式下对视频内容的理解表现出令人惊讶的强大性能，这得益于其使用的 AnyRes 技术。AnyRes 技术能够自然地将高分辨率图像表示为多张图像。由于视频可以被视为一组帧（类似于 LLaVa-NeXT 中的一组图像），该技术可以自然地推广到视频表示上。当前版本的 LLaVA-NeXT 利用了 AnyRes，并在 LLaVA-Next 的基础上，使用视频数据通过监督微调（SFT）进行训练，以实现更好的视频理解能力。该模型目前在 [VideoMME bench](https://huggingface.co/papers/2405.21075) 上处于开源模型中的 SOTA 水平。

该博客的引言如下：

2024 年 1 月 30 日，我们发布了 LLaVA-NeXT，这是一个完全基于文本-图像数据训练的开源大型多模态模型（LMM）。借助所提出的 AnyRes 技术，它在推理、OCR 和世界知识方面提升了能力，在一系列基于图像的多模态理解任务中展现出卓越的性能，甚至在 MMMU 和 MathVista 等多个图像基准测试中超越了 Gemini-Pro。

**在今天的探索中，我们将深入探讨 LLaVA-NeXT 在视频理解任务中的表现。我们发现，LLaVA-NeXT 在理解视频内容方面出人意料地表现出色。当前用于视频的 LLaVA-NeXT 版本包含以下几项改进：**

- 基于 AnyRes 的零样本视频表征能力：AnyRes 技术能够自然地将高分辨率图像表示为多张图像，使其可被预训练的 VIT 处理，并将它们组合成一个拼接序列。该技术可自然地推广到视频（由多帧组成）的表征，使得仅使用图像训练的 LLaVA-Next 模型在视频任务上也能表现出令人惊讶的良好效果。值得注意的是，这是 LMM 首次展现出强大的零样本模态迁移能力。
- 在长视频上进行推理时，长度泛化能力带来了性能提升。线性缩放技术实现了长度泛化，使 LLaVA-NeXT 能够有效处理超出 LLM “max_token_length” 限制的长视频。
- 强大的视频理解能力。(1) LLaVA-Next-Image 结合了上述两种技术，其零样本性能优于在视频上微调的开源 LMM。(2) LLaVA-Next-Video 在视频数据上对 LLaVA-Next-Image 进行进一步的监督微调 (SFT)，与 LLaVA-Next-Image 相比，实现了更好的视频理解能力。(3) LLaVA-Next-Video-DPO 使用直接偏好优化 (DPO) 将模型响应与 AI 反馈对齐，展现出显著的性能提升。
- 使用 SGLang 实现高效的部署与推理。它可将视频任务的推理速度提升 5 倍，从而支持更具可扩展性的服务，例如百万级视频重新描述。请参阅我们仓库中的说明。**

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

## 使用技巧

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

- Llava-Next 针对图像使用不同数量的 patch，因此除了处理输入时执行的填充外，还必须在建模代码内部对输入进行填充。如果模型处于 `eval()` 模式，默认设置为“左侧填充”，否则为“右侧填充”。

> [!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`。

### 使用聊天模板格式化提示  

每个 **checkpoint** 都使用特定的提示格式进行训练，具体取决于底层的大语言模型骨干网络。为确保格式正确，请使用处理器的 `apply_chat_template` 方法。

**重要：**

- 您必须构建对话历史——直接传入普通字符串将无法正常工作。
- 每条消息应为一个字典，包含 `"role"` 和 `"content"` 键。
- `"content"` 应为包含不同模态（如 `"text"` 和 `"image"`）的字典列表。

以下是一个输入结构的示例。我们将使用 [LLaVA-NeXT-Video-7B-hf](https://huggingface.co/llava-hf/LLaVA-NeXT-Video-7B-hf) 以及包含视频和图像的对话历史。

```python
from transformers import LlavaNextVideoProcessor

processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

conversation = [
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions."},
            ],
    },
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "What’s shown in this image?"},
            {"type": "image"},
            ],
    },
    {
        "role": "assistant",
        "content": [{"type": "text", "text": "This image shows a red stop sign."},]
    },
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video"},
            ],
    },
]

text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

# Note that the template simply formats your prompt, you still have to tokenize it and obtain pixel values for your visuals
print(text_prompt)
```

🚀 **附加内容：**如果你使用的是 `transformers>=4.49.0`，还可以从 `apply_chat_template` 获取向量化输出。有关如何使用它的更多详细信息，请参阅下方的 **使用示例**。

## 使用示例

### 单一媒体模式

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

```python
from huggingface_hub import hf_hub_download

from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor

# Load the model in half-precision
model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", device_map="auto")
processor = LlavaNextVideoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

# Load the video as an np.array, sampling uniformly 8 frames (can sample more for longer videos)
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")

conversation = [
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video", "path": video_path},
            ],
    },
]

inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, 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)
```

### 混合媒体模式

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

```python

# Generate from image and video mixed inputs
conversation = [
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "How many cats are there in the image?"},
            {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
            ],
    },
    {

        "role": "assistant",
        "content": [{"type": "text", "text": "There are two cats"}],
    },
    {

        "role": "user",
        "content": [
            {"type": "text", "text": "Why is this video funny?"},
            {"type": "video", "path": video_path},
            ],
    },
]
inputs = processor.apply_chat_template(conversation, num_frames=8, add_generation_prompt=True, tokenize=True, return_dict=True, 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 LlavaNextVideoForConditionalGeneration

# 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 = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-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 LlavaNextVideoForConditionalGeneration

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

## LlavaNextVideoConfig[[transformers.LlavaNextVideoConfig]]

#### transformers.LlavaNextVideoConfig[[transformers.LlavaNextVideoConfig]]

```python
transformers.LlavaNextVideoConfig(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 = 32001, video_token_index: int = 32000, projector_hidden_act: str = 'gelu', vision_feature_select_strategy: typing.Literal['default', 'full'] = 'default', vision_feature_layer: int | list[int] = -2, multimodal_projector_bias: bool = True, tie_word_embeddings: bool = False, image_grid_pinpoints: list | None = None, spatial_pool_mode: str = 'average', spatial_pool_stride: int = 2, image_seq_length: int = 576, video_seq_length: int = 288)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/configuration_llava_next_video.py#L32)

**参数：**

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

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

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

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

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

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

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

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

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

image_grid_pinpoints (`List`, *可选*, 默认为 `[[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]`) : 用于处理高分辨率图像的可用分辨率列表。列表中的每个元素应为 `(height, width)` 形式的元组或列表。

spatial_pool_mode (`str`，*可选*，默认为 `"average"`)：用于视频的池化模式。可以是 "average"、"max" 或 "conv"。

spatial_pool_stride (`int`，*可选*，默认为 2)：用于视频池化层的步幅。

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

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

这是用于存储 LlavaNextVideoModel 配置的类。它根据指定的参数实例化 Llava Next Video 模型，并定义模型架构。使用默认值实例化配置将得到与 [llava-hf/LLaVA-NeXT-Video-7B-hf](https://huggingface.co/llava-hf/LLaVA-NeXT-Video-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 LlavaNextVideoForConditionalGeneration, LlavaNextVideoConfig, CLIPVisionConfig, LlamaConfig

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

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

>>> configuration = LlavaNextVideoConfig(vision_config, text_config)

>>> model = LlavaNextVideoForConditionalGeneration(configuration)

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

## LlavaNextVideoProcessor[[transformers.LlavaNextVideoProcessor]]

#### transformers.LlavaNextVideoProcessor[[transformers.LlavaNextVideoProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/processing_llava_next_video.py#L31)

**参数：**

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

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

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

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

patch_size (`int`, *可选*) : 视觉塔的补丁大小。

vision_feature_select_strategy (`str`, *可选*) : 用于从视觉主干中选择视觉特征的特征选择策略。应与模型配置中的设置保持一致

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

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

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

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

[LlavaNextVideoProcessor](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoProcessor) 提供了 [LlavaNextVideoVideoProcessor](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoVideoProcessor)、[LlavaNextImageProcessor](/docs/transformers/main/zh/model_doc/granitevision#transformers.LlavaNextImageProcessor) 和 `tokenizer_class` 的所有功能。有关更多信息，请参阅 [~LlavaNextVideoVideoProcessor](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoVideoProcessor)、[~LlavaNextImageProcessor](/docs/transformers/main/zh/model_doc/granitevision#transformers.LlavaNextImageProcessor) 和 `~tokenizer_class`。

## LlavaNextVideoVideoProcessor[[transformers.LlavaNextVideoVideoProcessor]]

#### transformers.LlavaNextVideoVideoProcessor[[transformers.LlavaNextVideoVideoProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/video_processing_llava_next_video.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 类。

构造一个 LlavaNextVideoVideoProcessor 视频处理器。

## LlavaNextVideoModel[[transformers.LlavaNextVideoModel]]

#### transformers.LlavaNextVideoModel[[transformers.LlavaNextVideoModel]]

```python
transformers.LlavaNextVideoModel(config: LlavaNextVideoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/modeling_llava_next_video.py#L264)

**参数：**

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

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

该模型继承自 [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.LlavaNextVideoModel.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, image_sizes: typing.Optional[torch.LongTensor] = 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/llava_next_video/modeling_llava_next_video.py#L463)

**参数：**

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` 来处理视频）。

image_sizes (`torch.LongTensor`，形状为 `(batch_size, 2)`，*可选*)：批次中各图像的尺寸，每张图像为 (height, width)。

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"`)：用于从视觉骨干网络中选择视觉特征的特征选择策略。可以是 `"default"` 或 `"full"` 之一。如果为 `"default"`，则从视觉特征中移除 CLS token。如果为 `"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)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

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

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

[LlavaNextVideoModel](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoModel) 的 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.LlavaNextVideoModel.get_image_features]]

```python
get_image_features(pixel_values: Tensor, image_sizes: 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/llava_next_video/modeling_llava_next_video.py#L350)

**参数：**

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

image_sizes (`torch.Tensor`，形状为 `(num_images, 2)`)：每张图片的实际尺寸 (H, W)。

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

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`)：批次中图像的尺寸，每张图像为 (height, width)。

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`），其包含的元素取决于配置（[LlavaNextVideoConfig](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoConfig)）和输入。

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

- **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.LlavaNextVideoModel.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/llava_next_video/modeling_llava_next_video.py#L422)

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

#### get_video_features[[transformers.LlavaNextVideoModel.get_video_features]]

```python
get_video_features(pixel_values_videos: 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/llava_next_video/modeling_llava_next_video.py#L552)

**参数：**

pixel_values_videos (`torch.Tensor]`，形状为 `(batch_size, num_frames, channels, height, width)`)：与输入视频对应的张量。

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

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`），其包含的元素取决于配置（[LlavaNextVideoConfig](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoConfig)）和输入。

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

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

#### pack_image_features[[transformers.LlavaNextVideoModel.pack_image_features]]

```python
pack_image_features(image_features, image_sizes, vision_feature_select_strategy, image_newline = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/modeling_llava_next_video.py#L283)

**参数：**

image_features (`list[torch.Tensor]`，长度为 num_images，每个张量的形状为 `(num_patches, image_length, embed_dim)`)：图像特征张量列表，每个张量包含所有 patch 的视觉特征。

image_sizes (`torch.Tensor`，形状为 `(num_images, 2)`)：每张图片的实际尺寸 (H, W)。

vision_feature_select_strategy (`str`) : 用于从视觉主干网络中选择视觉特征的特征选择策略。

image_newline (`torch.Tensor`，形状为 `(embed_dim)`) : 新的换行嵌入向量。

**返回值：**

image_features (`torch.Tensor`，形状为 `(all_feat_len, embed_dim)`) feature_lens (`list[int]`) image_features 中每张图片的 token 长度

将每个 image_feature 重塑、去除填充，然后打包成一个包含所有视觉向量的单一 image_features 张量。

## LlavaNextVideoForConditionalGeneration[[transformers.LlavaNextVideoForConditionalGeneration]]

#### transformers.LlavaNextVideoForConditionalGeneration[[transformers.LlavaNextVideoForConditionalGeneration]]

```python
transformers.LlavaNextVideoForConditionalGeneration(config: LlavaNextVideoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_next_video/modeling_llava_next_video.py#L608)

**参数：**

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

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

该模型继承自 [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.LlavaNextVideoForConditionalGeneration.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, image_sizes: typing.Optional[torch.LongTensor] = 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/llava_next_video/modeling_llava_next_video.py#L661)

**参数：**

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` 来处理视频）。

image_sizes (`torch.LongTensor`，形状为 `(batch_size, 2)`，*可选*)：批次中各图像的尺寸，每张图像为 (height, width)。

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)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

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

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

[LlavaNextVideoForConditionalGeneration](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoForConditionalGeneration) 的 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 av
>>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration

>>> 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 = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-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 (model was trained with 32 frames per video, but this video is short)
>>> 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, return_tensors="pt").to(model.device)

>>> # load an image to generate from an image
>>> prompt = "USER:<image>\nWhat is shown in this image? ASSISTANT:"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> inputs_image = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

>>> # Generate from video
>>> generate_ids = model.generate(**inputs_video, max_length=50)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER:\nWhy is this video funny? ASSISTANT: The humor in this video comes from the unexpected and endearing sight of a baby wearing glasses and (...)"

>>> # Generate from image
>>> generate_ids = model.generate(**inputs_image, max_length=30)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER: \nWhat's the content of the image? ASSISTANT: The image shows a red stop sign on a pole, with a traditional Chinese archway (...)"
```

#### get_image_features[[transformers.LlavaNextVideoForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, image_sizes: 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/llava_next_video/modeling_llava_next_video.py#L629)

**参数：**

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

image_sizes (`torch.Tensor`，形状为 `(num_images, 2)`)：每张图片的实际尺寸 (H, W)。

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

image_sizes (`torch.Tensor`，形状为 `(batch_size, 2)`)：批次中图像的尺寸，每张图像为 (height, width)。

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`），其包含的元素取决于配置（[LlavaNextVideoConfig](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoConfig)）和输入。

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration

>>> model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

#### get_video_features[[transformers.LlavaNextVideoForConditionalGeneration.get_video_features]]

```python
get_video_features(pixel_values_videos: 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/llava_next_video/modeling_llava_next_video.py#L779)

**参数：**

pixel_values_videos (`torch.Tensor]`，形状为 `(batch_size, num_frames, channels, height, width)`)：与输入视频对应的张量。

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

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`），其包含的元素取决于配置（[LlavaNextVideoConfig](/docs/transformers/main/zh/model_doc/llava_next_video#transformers.LlavaNextVideoConfig)）和输入。

- **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 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration

>>> model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")
>>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

