Transformers 文件

LLaVa-NeXT-Video

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

LLaVa-NeXT-影片

PyTorch FlashAttention SDPA

概述

LLaVa-NeXT-Video 模型由 Yuanhan Zhang, Bo Li, Haotian Liu, Yong Jae Lee, Liangke Gui, Di Fu, Jiashi Feng, Ziwei Liu, Chunyuan Li 在 LLaVA-NeXT: 一個強大的零樣本影片理解模型 中提出。LLaVa-NeXT-Video 透過在影片和影像資料集上進行混合微調,從而提高了模型在影片上的效能,以改進 LLaVa-NeXT

LLaVA-NeXT 令人驚訝地在零樣本影片內容理解方面表現出色,這得益於其使用的 AnyRes 技術。AnyRes 技術自然地將高解析度影像表示為多個影像。這種技術自然地可以推廣到表示影片,因為影片可以被視為一組幀(類似於 LLaVa-NeXT 中的一組影像)。LLaVA-NeXT 的當前版本利用 AnyRes,並在 LLaVA-Next 的基礎上對影片資料進行監督微調 (SFT) 訓練,以實現更好的影片理解能力。該模型目前在 VideoMME 基準 上是開源模型中的最新 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 透過在影片資料上進一步監督微調 (SFT) LLaVA-Next-Image,實現了比 LLaVA-Next-Image 更好的影片理解能力。(3) LLaVA-Next-Video-DPO,它使用直接偏好最佳化 (DPO) 將模型響應與 AI 反饋對齊,顯示出顯著的效能提升。
  • 使用 SGLang 進行高效部署和推理。它使影片任務的推理速度提高了 5 倍,從而可以進行更具可擴充套件性的服務,例如百萬級別的影片重字幕。請參閱我們倉庫中的說明。**

此模型由 RaushanTurganbay 貢獻。原始程式碼可在 此處 找到。

使用技巧

  • 我們建議使用者在計算批生成時使用 padding_side="left",因為它能帶來更準確的結果。只需確保在生成前呼叫 processor.tokenizer.padding_side = "left"
  • Llava-Next 對影像使用不同數量的補丁,因此除了在處理輸入時進行的填充之外,還必須在建模程式碼內部填充輸入。如果模型處於 eval() 模式,預設設定為“左填充”,否則為“右填充”。

[!注意] 版本 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 將嘗試推斷每張影像所需的影像標記數量,並用與標記數量相同的 <image> 佔位符擴充套件文字。通常每張影像大約有 500 個標記,因此請確保文字沒有被截斷,否則在合併嵌入時會出現故障。這些屬性可以從模型配置中獲取,例如 model.config.vision_config.patch_sizemodel.config.vision_feature_select_strategy。如果視覺骨幹添加了 CLS 標記,則 num_additional_image_tokens 應為 1;如果沒有新增額外內容到視覺補丁,則為 0

使用聊天模板格式化提示

每個 **檢查點** 都經過特定提示格式的訓練,具體取決於底層大型語言模型骨幹。為確保格式正確,請使用處理器的 apply_chat_template 方法。

重要提示

  • 您必須構建一個對話歷史記錄——傳遞一個純字串將不起作用。
  • 每條訊息都應該是一個帶有 "role""content" 鍵的字典。
  • "content" 應該是一個包含不同模態(如 "text""image")的字典列表。

以下是如何構建輸入的一個示例。我們將使用 LLaVA-NeXT-Video-7B-hf 以及影片和影像的對話歷史。

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)的示例程式碼

from huggingface_hub import hf_hub_download
import torch
from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor

# Load the model in half-precision
model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", torch_dtype=torch.float16, 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")

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

混合媒體模式

該模型還可以從交錯的影像-影片輸入中生成。但請注意,它未在交錯的影像-影片設定中進行訓練,這可能會影響效能。以下是混合媒體輸入的使用示例,將以下行新增到上述程式碼片段中


# 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")

# 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。有關安裝說明和最新後端更新,請訪問 此連結

我們重視您的反饋,以幫助在完整發布之前發現錯誤!請檢視 這些文件 獲取更多詳細資訊和反饋連結。

然後,只需透過新增 BitsAndBytesConfig 載入量化模型,如下所示

from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor

# 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 大幅加速模型推理,它是模型內部注意力機制的更快實現。

首先,請確保安裝最新版本的 Flash Attention 2

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

此外,您應該擁有與 Flash-Attention 2 相容的硬體。有關更多資訊,請參閱 Flash Attention 倉庫 的官方文件。FlashAttention-2 只能在模型以 torch.float16torch.bfloat16 載入時使用。

要使用 Flash Attention-2 載入和執行模型,只需在載入模型時新增 `attn_implementation="flash_attention_2"`,如下所示

from transformers import LlavaNextVideoForConditionalGeneration

model = LlavaNextVideoForConditionalGeneration.from_pretrained(
    "llava-hf/LLaVA-NeXT-Video-7B-hf", 
    torch_dtype=torch.float16, 
    attn_implementation="flash_attention_2",
).to(0)

LlavaNextVideoConfig

class transformers.LlavaNextVideoConfig

< >

( vision_config = None text_config = None image_token_index = 32001 projector_hidden_act = 'gelu' multimodal_projector_bias = True vision_feature_select_strategy = 'default' vision_feature_layer = -2 image_grid_pinpoints = None tie_word_embeddings = False video_token_index = 32000 spatial_pool_mode = 'average' spatial_pool_stride = 2 image_seq_length = 576 video_seq_length = 288 **kwargs )

引數

  • vision_config (Union[AutoConfig, dict], 可選, 預設為 CLIPVisionConfig) — 視覺骨幹的配置物件或字典。
  • text_config (Union[AutoConfig, dict], 可選, 預設為 LlamaConfig) — 文字骨幹的配置物件或字典。
  • image_token_index (int, 可選, 預設為 32001) — 用於編碼影像提示的影像標記索引。
  • projector_hidden_act (str, 可選, 預設為 "gelu") — 多模態投影器使用的啟用函式。
  • multimodal_projector_bias (bool, 可選, 預設為 True) — 是否在多模態投影器中使用偏差。
  • vision_feature_select_strategy (str, 可選, 預設為 "default") — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。可以是 "default""full"。如果為 "default",則從視覺特徵中刪除 CLS 標記。如果為 "full",則使用完整的視覺特徵。
  • vision_feature_layer (Union[int, list[int]], 可選, 預設為 -2) — 選擇視覺特徵的層索引。如果提供了多個索引,則相應索引的視覺特徵將被連線起來形成視覺特徵。
  • image_grid_pinpoints (List, 可選, 預設為 [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]) — 用於處理高解析度影像的可能解析度列表。列表中的每個項都應為 (height, width) 形式的元組或列表。
  • tie_word_embeddings (bool, 可選, 預設為 False) — 模型的輸入和輸出詞嵌入是否應該繫結。
  • video_token_index (int, 可選, 預設為 32000) — 用於編碼影像提示的影片標記索引。
  • spatial_pool_mode (str, 可選, 預設為 "average") — 用於影片的池化模式。可以是“average”、“max”或“conv”。
  • spatial_pool_stride (int, 可選, 預設為 2) — 影片池化層中使用的步幅。
  • image_seq_length (int, 可選, 預設為 576) — 單個影像嵌入的序列長度。
  • video_seq_length (int, 可選, 預設為 288) — 單個影片嵌入的序列長度。

這是一個配置類,用於儲存 LlavaNextVideoForConditionalGeneration 的配置。它用於根據指定的引數例項化 Llava-NeXT 模型,定義模型架構。使用預設值例項化配置將產生與 llava-hf/LLaVA-NeXT-Video-7B-hf 模型相似的配置。配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

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

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

引數

  • video_processor (LlavaNextVideoProcessor, 可選) — 影片處理器是一個必需的輸入。
  • image_processor (LlavaNextImageProcessor, 可選) — 影像處理器是一個必需的輸入。
  • tokenizer (LlamaTokenizerFast, 可選) — 分詞器是一個必需的輸入。
  • chat_template (str, 可選) — 將在分詞器的 apply_chat_template 中使用的 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 或其他額外標記,則無需設定此引數。

構建一個 LLaVa-NeXT-影片處理器,它將 LLaVa-NeXT 影像處理器、LLaVa-NeXT-影片處理器和 LLaMa 分詞器封裝在一個處理器中。

LlavaNextVideoProcessor 提供了 LlavaNextImageProcessorLlavaNextVideoImageProcessorLlamaTokenizerFast 的所有功能。有關更多資訊,請參閱 __call__()decode()

batch_decode

< >

( *args **kwargs )

此方法將其所有引數轉發到 LlamaTokenizerFast 的 batch_decode()。有關更多資訊,請參閱此方法的文件字串。

decode

< >

( *args **kwargs )

此方法將其所有引數轉發給 LlamaTokenizerFast 的 decode()。有關更多資訊,請參閱此方法的文件字串。

LlavaNextVideoImageProcessor

class transformers.LlavaNextVideoImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None image_grid_pinpoints: typing.Optional[list] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

引數

  • do_resize (bool, optional, defaults to True) — 是否將影像的(高度、寬度)尺寸調整為指定的 size。可在 preprocess 方法中透過 do_resize 覆蓋。
  • size (dict[str, int] optional, defaults to {"shortest_edge" -- 224}): 調整大小後的影像尺寸。影像的最短邊將調整為 size["shortest_edge"],最長邊將調整為保持輸入寬高比。可在 preprocess 方法中透過 size 覆蓋。
  • image_grid_pinpoints (List optional, defaults to [[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]) — 用於處理高解析度影像的可能解析度列表。將根據影像的原始尺寸選擇最佳解析度。可在 preprocess 方法中透過 image_grid_pinpoints 覆蓋。不用於影片處理。
  • resample (PILImageResampling, optional, defaults to Resampling.BICUBIC) — 調整影像大小時使用的重取樣濾鏡。可在 preprocess 方法中透過 resample 覆蓋。
  • do_center_crop (bool, optional, defaults to True) — 是否將影像中心裁剪為指定的 crop_size。可在 preprocess 方法中透過 do_center_crop 覆蓋。
  • crop_size (dict[str, int] optional, defaults to 224) — 應用 center_crop 後輸出影像的尺寸。可在 preprocess 方法中透過 crop_size 覆蓋。
  • do_rescale (bool, optional, defaults to True) — 是否按指定的比例 rescale_factor 重新縮放影像。可在 preprocess 方法中透過 do_rescale 覆蓋。
  • rescale_factor (int or float, optional, defaults to 1/255) — 重新縮放影像時使用的比例因子。可在 preprocess 方法中透過 rescale_factor 覆蓋。
  • do_normalize (bool, optional, defaults to True) — 是否對影像進行標準化。可在 preprocess 方法中透過 do_normalize 覆蓋。
  • image_mean (float or list[float], optional, defaults to [0.48145466, 0.4578275, 0.40821073]) — 標準化影像時使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可在 preprocess 方法中透過 image_mean 引數覆蓋。
  • image_std (float or list[float], optional, defaults to [0.26862954, 0.26130258, 0.27577711]) — 標準化影像時使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可在 preprocess 方法中透過 image_std 引數覆蓋。
  • do_convert_rgb (bool, optional, defaults to True) — 是否將影像轉換為 RGB。

構造一個 LLaVa-NeXT-Video 影片處理器。基於 CLIPImageProcessor,並結合了每幀影片的處理。

preprocess

< >

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

引數

  • images (VideoInput) — 要預處理的影片。期望單個或批處理的影片,畫素值範圍為 0 到 255。如果傳入的影像畫素值在 0 到 1 之間,請設定 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否調整影片大小。
  • 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"> size (dict[str, int], optional, defaults to self.size) — 調整大小後的影片尺寸。影片的最短邊將調整為 size["shortest_edge"],最長邊將調整為保持輸入寬高比。
  • resample (int, optional, defaults to self.resample) — 調整影片大小時使用的重取樣濾鏡。可以是列舉 PILImageResampling 之一。僅當 do_resize 設定為 True 時有效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否對影片進行中心裁剪。
  • crop_size (dict[str, int], optional, defaults to self.crop_size) — 中心裁剪的尺寸。僅當 do_center_crop 設定為 True 時有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否重新縮放影片。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 設定為 True,用於重新縮放影片的比例因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否對影片進行標準化。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 用於標準化的幀均值。僅當 do_normalize 設定為 True 時有效。
  • image_std (float or list[float], optional, defaults to self.image_std) — 用於標準化的幀標準差。僅當 do_normalize 設定為 True 時有效。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否將影片轉換為 RGB。
  • return_tensors (str or TensorType, optional) — 要返回的張量型別。可以是以下之一:
    • 未設定:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回 tf.Tensor 批處理。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 批處理。
    • TensorType.NUMPY'np':返回 np.ndarray 批處理。
    • TensorType.JAX'jax':返回 jax.numpy.ndarray 批處理。
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • 未設定:使用輸入影像的通道維度格式。
  • input_data_format (ChannelDimension or str, optional) — 輸入影像的通道維度格式。如果未提供,將從輸入影像中推斷。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:影像格式為 (height, width)。

resize

< >

( image: ndarray size: dict resample: Resampling = <Resampling.BICUBIC: 3> data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

引數

  • image (np.ndarray) — 要調整大小的影像。
  • size (dict[str, int]) — 輸出影像的尺寸。
  • resample (PILImageResampling, optional, defaults to PILImageResampling.BICUBIC) — 調整影像大小時使用的重取樣濾鏡。
  • data_format (str or ChannelDimension, optional) — 影像的通道維度格式。如果未提供,將與輸入影像的格式相同。
  • input_data_format (ChannelDimension or str, optional) — 輸入影像的通道維度格式。如果未提供,將自動推斷。

調整影像大小。影像的最短邊將調整為 size["shortest_edge"],最長邊將調整為保持輸入寬高比。

LlavaNextVideoVideoProcessor

class transformers.LlavaNextVideoVideoProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.models.llava_next_video.video_processing_llava_next_video.LlavaNextVideoFastVideoProcessorInitKwargs] )

LlavaNextVideoModel

class transformers.LlavaNextVideoModel

< >

( config: LlavaNextVideoConfig )

引數

  • config (LlavaNextVideoConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法來載入模型權重。

Llava-Next 模型由一個視覺骨幹和一個沒有語言建模頭的語言模型組成。

此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。將其用作常規 PyTorch 模組,並參閱 PyTorch 文件以瞭解所有與一般用法和行為相關的事項。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None pixel_values_videos: FloatTensor = None image_sizes: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoModelOutputWithPast or tuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — 輸入序列詞彙表中令牌的索引。預設情況下會忽略填充。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參見 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參見 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • pixel_values_videos (torch.FloatTensor of shape (batch_size, num_frames, num_channels, image_size, image_size)) -- 對應於輸入影片的張量。畫素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 獲取。有關詳細資訊,請參見 LlavaNextVideoVideoProcessor.call()`。 LlavaProcessor 使用 LlavaNextVideoVideoProcessor 處理影片。
  • image_sizes (torch.LongTensor of shape (batch_size, 2), optional) — 批次中影像的尺寸,每個影像為(高度,寬度)。
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 用於避免對填充令牌索引執行注意力的掩碼。掩碼值選擇範圍為 [0, 1]

    • 1 表示 未被掩碼 的令牌,
    • 0 表示 被掩碼 的令牌。

    什麼是注意力掩碼?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 每個輸入序列令牌在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是位置 ID?

  • past_key_values (list[torch.FloatTensor], 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。通常由模型在解碼的先前階段返回,當 use_cache=Trueconfig.use_cache=True 時。

    允許兩種格式:

    • 一個 Cache 例項,參見我們的 kv cache 指南
    • 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量)。這也被稱為舊版快取格式。

    模型將輸出與輸入相同的快取格式。如果沒有傳入 past_key_values,則將返回舊版快取格式。

    如果使用了 past_key_values,使用者可以選擇只輸入形狀為 (batch_size, 1) 的最後一個 input_ids(那些沒有將其過去的鍵值狀態提供給此模型的),而不是所有形狀為 (batch_size, sequence_length)input_ids

  • inputs_embeds (torch.FloatTensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 可選地,您可以選擇直接傳入嵌入表示,而不是傳入 input_ids。如果您想對如何將 input_ids 索引轉換為關聯向量擁有比模型內部嵌入查詢矩陣更多的控制權,這將非常有用。
  • vision_feature_layer (Union[int, list[int], NoneType]) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線起來形成視覺特徵。
  • vision_feature_select_strategy (str, 可選) — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。可以是 "default""full" 之一。
  • use_cache (bool, 可選) — 如果設定為 True,將返回 past_key_values 鍵值狀態,可用於加速解碼(參見 past_key_values)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是純元組。
  • cache_position (torch.LongTensor,形狀為 (sequence_length)可選) — 描述輸入序列令牌在序列中位置的索引。與 position_ids 相反,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。

返回

transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoModelOutputWithPasttuple(torch.FloatTensor)

一個 transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoModelOutputWithPast 或一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),根據配置(LlavaNextVideoConfig)和輸入包含各種元素。

  • last_hidden_state (形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可選) — 模型最後一層輸出的隱藏狀態序列。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可選, 當 use_cache=Trueconfig.use_cache=True 時返回) — 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量)

    包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • hidden_states (tuple[torch.FloatTensor, ...], 可選, 當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 每個層的輸出一個)的形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple[torch.FloatTensor, ...], 可選, 當傳入 output_attentions=Trueconfig.output_attentions=True 時返回) — torch.FloatTensor 元組(每個層一個)的形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

  • image_hidden_states (torch.FloatTensor, 可選) — 一個大小為 (batch_size, num_images, sequence_length, hidden_size)torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的 image_hidden_states。

  • video_hidden_states (torch.FloatTensor, 可選) — 一個大小為 (batch_size * num_frames, num_videos, sequence_length, hidden_size)torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的 video_hidden_states。

LlavaNextVideoModel 的前向方法,重寫了 __call__ 特殊方法。

儘管前向傳播的實現需要在該函式中定義,但此後應呼叫 Module 例項,因為前者負責執行預處理和後處理步驟,而後者則默默忽略它們。

get_image_features

< >

( pixel_values: FloatTensor image_sizes: Tensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None ) image_features (listtorch.Tensor)

引數

  • pixel_values (torch.FloatTensor],形狀為 (batch_size, num_patches, channels, height, width)) — 對應於輸入影像的張量。
  • image_sizes (torch.Tensor,形狀為 (num_images, 2)) — 每張影像的實際尺寸 (高, 寬)。
  • vision_feature_layer (Union[int, list[int]], 可選) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線起來形成視覺特徵。
  • vision_feature_select_strategy (str, 可選) — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。可以是 "default""full"

返回

image_features (listtorch.Tensor)

影像特徵張量列表,每個張量包含所有補丁的所有視覺特徵,形狀為 (num_patches, image_length, embed_dim)

從視覺塔獲取影像最後隱藏狀態並應用多模態投影。

get_video_features

< >

( pixel_values: FloatTensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None ) video_features (listtorch.Tensor)

引數

  • pixel_values (torch.FloatTensor],形狀為 (batch_size, num_frames, channels, height, width)) — 對應於輸入影片的張量。畫素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 獲取。有關詳細資訊,請參閱 LlavaNextVideoVideoProcessor.__call__()LlavaProcessor 使用 LlavaNextVideoVideoProcessor 來處理影片。
  • vision_feature_layer (Union[int, list[int]], 可選) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線起來形成視覺特徵。
  • vision_feature_select_strategy (str, 可選) — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。可以是 "default""full"

返回

video_features (listtorch.Tensor)

影片特徵張量列表,每個張量包含所有補丁的所有視覺特徵,形狀為 (num_videos, video_length, embed_dim))。

從視覺塔獲取影片最後一個隱藏狀態,並應用多模態投影。

pack_image_features

< >

( image_features image_sizes vision_feature_select_strategy image_newline = None )

引數

  • image_features (list[torch.Tensor],長度為 num_images,每個形狀為 (num_patches, image_length, embed_dim)) — 影像特徵張量列表,每個張量包含所有補丁的所有視覺特徵。
  • image_sizes (torch.Tensor,形狀為 (num_images, 2)) — 每張影像的實際尺寸 (高, 寬)。
  • vision_feature_select_strategy (str) — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。
  • image_newline (torch.Tensor,形狀為 (embed_dim)) — 新行嵌入向量。

重塑、取消填充,然後將每個 image_feature 打包成一個包含所有視覺向量的單個 image_features 張量。

LlavaNextVideoForConditionalGeneration

class transformers.LlavaNextVideoForConditionalGeneration

< >

( config: LlavaNextVideoConfig )

引數

  • config (LlavaNextVideoConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法以載入模型權重。

LLAVA-NeXT 模型由一個視覺骨幹和一個語言模型組成。

此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。將其用作常規 PyTorch 模組,並參閱 PyTorch 文件以瞭解所有與一般用法和行為相關的事項。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None pixel_values_videos: FloatTensor = None image_sizes: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.models.llava_next_video.modeling_llava_next_video.KwargsForCausalLM] ) transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPasttuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)) — 詞彙表中輸入序列令牌的索引。填充將預設忽略。

    索引可以使用 AutoTokenizer 獲取。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size)) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • pixel_values_videos (torch.FloatTensor,形狀為 (batch_size, num_frames, num_channels, image_size, image_size)) — 對應於輸入影片的張量。畫素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 獲取。有關詳細資訊,請參閱 LlavaNextVideoVideoProcessor.__call__()LlavaProcessor 使用 LlavaNextVideoVideoProcessor 來處理影片。
  • image_sizes (torch.LongTensor,形狀為 (batch_size, 2)可選) — 批次中影像的大小,每張影像為 (高, 寬)。
  • attention_mask (torch.Tensor,形狀為 (batch_size, sequence_length)可選) — 掩碼,用於避免在填充令牌索引上執行注意力。掩碼值選擇範圍為 [0, 1]

    • 1 表示未掩碼的令牌,
    • 0 表示已掩碼的令牌。

    什麼是注意力掩碼?

  • position_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 每個輸入序列令牌在位置嵌入中的位置索引。選擇範圍為 [0, config.n_positions - 1]

    什麼是位置 ID?

  • past_key_values (list[torch.FloatTensor], 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。通常由模型在解碼的先前階段返回,當 use_cache=Trueconfig.use_cache=True 時。

    允許兩種格式:

    • 一個 Cache 例項,參見我們的 kv cache 指南
    • 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量)。這也被稱為舊版快取格式。

    模型將輸出與輸入相同的快取格式。如果沒有傳入 past_key_values,則將返回舊版快取格式。

    如果使用了 past_key_values,使用者可以選擇只輸入形狀為 (batch_size, 1) 的最後一個 input_ids(那些沒有將其過去的鍵值狀態提供給此模型的),而不是所有形狀為 (batch_size, sequence_length)input_ids

  • inputs_embeds (torch.FloatTensor,形狀為 (batch_size, sequence_length, hidden_size)可選) — 可選地,您可以選擇直接傳入嵌入表示,而不是傳入 input_ids。如果您想對如何將 input_ids 索引轉換為關聯向量擁有比模型內部嵌入查詢矩陣更多的控制權,這將非常有用。
  • vision_feature_layer (Union[int, list[int], NoneType]) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線起來形成視覺特徵。
  • vision_feature_select_strategy (str, 可選) — 用於從視覺骨幹中選擇視覺特徵的特徵選擇策略。可以是 "default""full" 之一。
  • labels (torch.LongTensor,形狀為 (batch_size, sequence_length)可選) — 用於計算掩碼語言建模損失的標籤。索引應在 [0, ..., config.vocab_size] 或 -100 之間(參見 input_ids 文件字串)。索引設定為 -100 的令牌將被忽略(掩碼),損失只針對標籤在 [0, ..., config.vocab_size] 中的令牌計算。
  • use_cache (bool, 可選) — 如果設定為 True,將返回 past_key_values 鍵值狀態,可用於加速解碼(參見 past_key_values)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是純元組。
  • cache_position (torch.LongTensor,形狀為 (sequence_length)可選) — 描述輸入序列令牌在序列中位置的索引。與 position_ids 相反,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。
  • logits_to_keep (Union[int, torch.Tensor], 預設為 0) — 如果是 int,則計算最後 logits_to_keep 個令牌的 logits。如果是 0,則計算所有 input_ids 的 logits(特殊情況)。僅在生成時才需要最後一個令牌的 logits,並且僅對其計算可以節省記憶體,這對於長序列或大詞彙量來說非常重要。如果是 torch.Tensor,則必須是 1D,對應於序列長度維度中要保留的索引。這在使用打包張量格式(批次和序列長度的單個維度)時非常有用。

返回

transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPasttuple(torch.FloatTensor)

一個 transformers.models.llava_next_video.modeling_llava_next_video.LlavaNextVideoCausalLMOutputWithPast 或一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),根據配置(LlavaNextVideoConfig)和輸入包含各種元素。

  • loss (torch.FloatTensor 形狀為 (1,)可選,當提供 labels 時返回) — 語言建模損失(用於下一個 token 預測)。

  • logits (形狀為 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 語言建模頭部的預測分數(SoftMax 之前的每個詞彙標記的分數)。

  • past_key_values (tuple(tuple(torch.FloatTensor)), 可選, 當 use_cache=Trueconfig.use_cache=True 時返回) — 長度為 config.n_layerstuple(torch.FloatTensor) 元組,每個元組包含 2 個形狀為 (batch_size, num_heads, sequence_length, embed_size_per_head) 的張量)

    包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見 past_key_values 輸入)加速順序解碼。

  • hidden_states (tuple[torch.FloatTensor], 可選, 當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 每個層的輸出一個)的形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple[torch.FloatTensor], 可選, 當傳入 output_attentions=Trueconfig.output_attentions=True 時返回) — torch.FloatTensor 元組(每個層一個)的形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

  • image_hidden_states (torch.FloatTensor, 可選) — 一個大小為 (batch_size * num_patches, num_images, sequence_length, hidden_size)` 的 torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的 image_hidden_states。

  • video_hidden_states (torch.FloatTensor, 可選) — 一個大小為 (batch_size * num_frames, num_videos, sequence_length, hidden_size)torch.FloatTensor。由視覺編碼器生成並投影最後一個隱藏狀態後的 video_hidden_states。

LlavaNextVideoForConditionalGeneration 的前向方法,重寫了 __call__ 特殊方法。

儘管前向傳播的實現需要在該函式中定義,但此後應呼叫 Module 例項,因為前者負責執行預處理和後處理步驟,而後者則默默忽略它們。

示例

>>> from PIL import Image
>>> import requests
>>> 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"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> 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 (...)"
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.