Transformers 文件
Video-LLaVA
並獲得增強的文件體驗
開始使用
Video-LLaVA
概述
Video-LLaVA 是一個開源多模態大型語言模型(LLM),透過在由 Llava1.5 和 VideChat 生成的多模態指令遵循資料上進行微調而訓練。它是一個基於 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 中提出。
論文摘要如下:
大型視覺-語言模型(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 貢獻。原始程式碼可以在 此處 找到。
[!注意] LLaVA 模型在 v4.46 版本之後會發出關於新增 `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 將嘗試推斷每張影像所需的影像標記數量,並用與標記數量相同的 `
` 佔位符擴充套件文字。通常每張影像大約 500 個標記,因此請確保文字未被截斷,否則在合併嵌入時會出現故障。這些屬性可以從模型配置中獲取,例如 `model.config.vision_config.patch_size` 或 `model.config.vision_feature_select_strategy`。如果視覺骨幹添加了 CLS 標記,則 `num_additional_image_tokens` 應為 `1`;如果沒有額外內容新增到視覺補丁,則為 `0`。
使用示例
單一媒體模式
該模型可以接受影像和影片作為輸入。以下是一個半精度(`torch.float16`)推理的示例程式碼
import av
import torch
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", torch_dtype=torch.float16, device_map="auto")
processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
# Load the video as an np.arrau, 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")
out = model.generate(**inputs, max_new_tokens=60)
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)
對於多輪對話,請將提示格式更改為
"USER: <video>\nWhat do you see in this video? ASSISTANT: A baby reading a book. USER: Why is the it funny? ASSISTANT:"
混合媒體模式
該模型還可以從交錯的影像-影片輸入中生成。但請注意,它並未在交錯的影像-影片設定中進行訓練,這可能會影響效能。以下是混合媒體輸入的示例用法,將以下行新增到上述程式碼片段中
from PIL import Image
import requests
# 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")
# 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 VideoLlavaForConditionalGeneration, BitsAndBytesConfig
# 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 大大加快模型推理速度,它是模型內部使用的注意力機制的更快實現。
首先,請確保安裝最新版本的 Flash Attention 2
pip install -U flash-attn --no-build-isolation
此外,您應該擁有與 Flash-Attention 2 相容的硬體。有關更多資訊,請參閱 flash attention 倉庫 的官方文件。FlashAttention-2 只能在模型以 `torch.float16` 或 `torch.bfloat16` 載入時使用。
要使用 Flash Attention-2 載入和執行模型,只需在載入模型時新增 `attn_implementation="flash_attention_2"`,如下所示
from transformers import VideoLlavaForConditionalGeneration
model = VideoLlavaForConditionalGeneration.from_pretrained(
"LanguageBind/Video-LLaVA-7B-hf",
torch_dtype=torch.float16,
attn_implementation="flash_attention_2",
).to(0)
VideoLlavaConfig
class transformers.VideoLlavaConfig
< 來源 >( vision_config = None text_config = None image_token_index = 32000 video_token_index = 32001 projector_hidden_act = 'gelu' vision_feature_select_strategy = 'default' vision_feature_layer = -2 image_seq_length = 256 video_seq_length = 2056 multimodal_projector_bias = True **kwargs )
引數
- vision_config (`VideoLlavaVisionConfig`, _可選_) — 自定義視覺配置或字典。如果未指定,預設為 `CLIPVisionConfig`。
- text_config (`Union[AutoConfig, dict]`, _可選_) — 文字主幹的配置物件。可以是 `LlamaConfig` 或 `MistralConfig` 中的任何一種。如果未指定,預設為 `LlamaConfig`。
- image_token_index (`int`, _可選_, 預設為 32000) — 用於編碼影像提示的影像標記索引。
- video_token_index (`int`, _可選_, 預設為 32001) — 用於編碼影像提示的影片標記索引。
- projector_hidden_act (`str`, _可選_, 預設為 `"gelu"`) — 多模態投影儀使用的啟用函式。
- vision_feature_select_strategy (`str`, _可選_, 預設為 `"default"`) — 用於從 CLIP 主幹中選擇視覺特徵的特徵選擇策略。可以是 `"full"` 以選擇所有特徵,也可以是 `"default"` 以選擇不帶 `CLS` 的特徵。
- vision_feature_layer (`Union[int, list[int]]`, _可選_, 預設為 -2) — 選擇視覺特徵的層索引。如果提供多個索引,則相應索引的視覺特徵將被連線以形成視覺特徵。
- image_seq_length (`int`, _可選_, 預設為 256) — 一幅影像嵌入的序列長度。
- video_seq_length (`int`, _可選_, 預設為 2056) — 一個影片嵌入的序列長度。
- multimodal_projector_bias (`bool`, _可選_, 預設為 `True`) — 是否在多模態投影儀中使用偏置。
這是用於儲存 VideoLlavaForConditionalGeneration 配置的配置類。它用於根據指定引數例項化 VideoLlava 模型,定義模型架構。使用預設值例項化配置將產生與 LanguageBind/Video-LLaVA-7B-hf 相似的配置。
例如:LanguageBind/Video-LLaVA-7B-hf
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請參閱 PretrainedConfig 的文件。
示例
>>> 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
class transformers.VideoLlavaImageProcessor
< 來源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = 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`, _可選_, 預設為 `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 影像處理器。
預處理
< 來源 >( images: typing.Optional[list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]]] = None videos: typing.Optional[list[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']]]]] = None 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 (`ImageInput`, _可選_) — 要預處理的影像列表。期望單個或批處理影像,畫素值範圍從 0 到 255。如果傳入的影像畫素值在 0 到 1 之間,請設定 `do_rescale=False`。
- videos (`VideoInput`, _可選_) — 要預處理的影片列表。期望單個或批處理影片,畫素值範圍從 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.TENSORFLOW
或'tf'
:返回tf.Tensor
型別的批處理。TensorType.PYTORCH
或'pt'
:返回torch.Tensor
型別的批處理。TensorType.NUMPY
或'np'
:返回np.ndarray
型別的批處理。TensorType.JAX
或'jax'
:返回jax.numpy.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) 格式。
預處理一張或一批影像。
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 )
調整影像大小。影像的最短邊調整為 size[“shortest_edge”],最長邊保持輸入縱橫比不變。
VideoLlavaVideoProcessor
類 transformers.VideoLlavaVideoProcessor
< 源 >( **kwargs: typing_extensions.Unpack[transformers.models.video_llava.video_processing_video_llava.VideoLlavaFastVideoProcessorInitKwargs] )
VideoLlavaProcessor
類 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 )
引數
- image_processor (VideoLlavaImageProcessor, 可選) — 影像處理器是必需的輸入。
- video_processor (VideoLlavaVideoProcessor, 可選) — 影片處理器是必需的輸入。
- tokenizer (LlamaTokenizerFast, 可選) — 分詞器是必需的輸入。
- 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 或其他額外標記附加,則無需設定此引數。
構建一個 VideoLlava 處理器,它將 VideoLlava 影像處理器和 Llava 分詞器封裝到一個單一的處理器中。
VideoLlavaProcessor 提供 VideoLlavaImageProcessor 和 LlamaTokenizerFast 的所有功能。有關更多資訊,請參閱 __call__()
和 decode()。
此方法將其所有引數轉發給 LlamaTokenizerFast 的 batch_decode()。有關更多資訊,請參閱此方法的文件字串。
VideoLlavaModel
類 transformers.VideoLlavaModel
< 源 >( config: VideoLlavaConfig )
引數
- config (VideoLlavaConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不載入與模型關聯的權重,僅載入配置。檢視 from_pretrained() 方法載入模型權重。
VideoLlava 模型,由視覺骨幹網路和無語言建模頭的語言模型組成。
此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的一般方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件中與一般用法和行為相關的所有事項。
forward
< 源 >( input_ids: LongTensor = None pixel_values_images: FloatTensor = None pixel_values_videos: FloatTensor = 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.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
形狀為(batch_size, sequence_length)
) — 詞彙表中輸入序列標記的索引。預設情況下會忽略填充。可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參見 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values_images (
torch.FloatTensor
形狀為(batch_size, num_channels, image_size, image_size)
) — 對應於輸入影像的張量。畫素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 獲取。有關詳細資訊,請參閱 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([`LlavaProcessor`] 使用 VideoLlavaImageProcessor 處理影像)。 - 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) 獲取。有關詳細資訊,請參閱 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([`LlavaProcessor`] 使用 VideoLlavaImageProcessor 處理影片)。 - 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]
。 - past_key_values (
list[torch.FloatTensor]
, 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常包括模型在先前解碼階段返回的past_key_values
,當use_cache=True
或config.use_cache=True
時。允許兩種格式:
- Cache 例項,請參閱我們的 kv 快取指南;
config.n_layers
長度的tuple(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.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 tuple(torch.FloatTensor)
一個 transformers.models.video_llava.modeling_video_llava.VideoLlavaModelOutputWithPast
或 torch.FloatTensor
元組(如果傳遞 return_dict=False
或當 config.return_dict=False
時),包含根據配置(VideoLlavaConfig)和輸入的不同元素。
-
last_hidden_state (
<class 'torch.FloatTensor'>.last_hidden_state
形狀為(batch_size, sequence_length, hidden_size)
, 預設為None
) — 模型最後一層的隱藏狀態序列。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可選, 當傳遞use_cache=True
或當config.use_cache=True
時返回) —config.n_layers
長度的tuple(torch.FloatTensor)
元組,每個元組包含 2 個形狀為(batch_size, num_heads, sequence_length, embed_size_per_head)
的張量)包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見
past_key_values
輸入)加速順序解碼。 -
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_hidden_states (
torch.FloatTensor
, 可選) — 形狀為 (batch_size, num_images, sequence_length, hidden_size) 的torch.FloatTensor
。由視覺編碼器生成並投影最後隱藏狀態後的模型影像隱藏狀態。 -
video_hidden_states (
torch.FloatTensor
, 可選) — 形狀為(batch_size * num_frames, num_videos, sequence_length, hidden_size)
的torch.FloatTensor
。由視覺編碼器生成並投影最後隱藏狀態後的模型影片隱藏狀態。
VideoLlavaModel 的 forward 方法,覆蓋了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但在此之後應該呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。
get_image_features
< 源 >( pixel_values_images: FloatTensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None vision_feature_select_strategy: typing.Optional[str] = None ) → image_features (torch.Tensor
)
引數
- pixel_values_images (
torch.FloatTensor]
,形狀為(batch_size, channels, height, width)
) — 對應於輸入影像的張量。 - vision_feature_layer (
Union[int, list[int]]
, 可選) — 用於選擇視覺特徵的層索引。如果提供了多個索引,則對應索引的視覺特徵將被連線起來形成視覺特徵。 - vision_feature_select_strategy (
str
, 可選) — 用於從視覺骨幹網路中選擇視覺特徵的特徵選擇策略。可以是"default"
或"full"
之一。
返回
image_features (torch.Tensor
)
形狀為 (num_images, image_length, embed_dim)
的影像特徵張量。
從視覺塔獲取影像最後隱藏狀態並應用多模態投影。
get_video_features
< source >( pixel_values_videos: FloatTensor vision_feature_layer: typing.Union[int, list[int], NoneType] = None ) → video_features (torch.Tensor
)
引數
- pixel_values_videos (
torch.FloatTensor]
,形狀為(batch_size, num_frames, channels, height, width)
) — 對應於輸入影片的張量。 - vision_feature_layer (
Union[int, list[int]]
, 可選) — 用於選擇視覺特徵的層索引。如果提供了多個索引,則對應索引的視覺特徵將被連線起來形成視覺特徵。
返回
video_features (torch.Tensor
)
影片特徵張量,形狀為 (num_videos * num_frames, image_length, embed_dim)
)。frames (int
):影片的幀數。
從視覺塔中獲取影片的最後一個隱藏狀態並應用多模態投影。
VideoLlavaForConditionalGeneration
class transformers.VideoLlavaForConditionalGeneration
< source >( config: VideoLlavaConfig )
引數
- config (VideoLlavaConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法以載入模型權重。
VideoLlava 模型由視覺骨幹和語言模型組成。
此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的一般方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件中與一般用法和行為相關的所有事項。
forward
< source >( input_ids: LongTensor = None pixel_values_images: FloatTensor = None pixel_values_videos: FloatTensor = 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.video_llava.modeling_video_llava.KwargsForCausalLM] ) → transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
or tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
,形狀為(batch_size, sequence_length)
) — 詞彙表中輸入序列 token 的索引。預設情況下會忽略填充。索引可以透過 AutoTokenizer 獲取。詳情請參閱 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values_images (
torch.FloatTensor
,形狀為(batch_size, num_channels, image_size, image_size)) -- 對應於輸入影像的張量。畫素值可以使用 [AutoImageProcessor](/docs/transformers/v4.53.3/en/model_doc/auto#transformers.AutoImageProcessor) 獲取。詳見 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([]
LlavaProcessor`] 使用 VideoLlavaImageProcessor 處理影像)。 - 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) 獲取。詳見 [VideoLlavaImageProcessor.__call__()](/docs/transformers/v4.53.3/en/model_doc/deformable_detr#transformers.DeformableDetrFeatureExtractor.__call__)([]
LlavaProcessor`] 使用 VideoLlavaImageProcessor 處理影片)。 - attention_mask (
torch.Tensor
,形狀為(batch_size, sequence_length)
, 可選) — 掩碼,用於避免在填充 token 索引上執行注意力。掩碼值選擇在[0, 1]
之間:- 1 表示**未被掩碼**的 token,
- 0 表示**被掩碼**的 token。
- position_ids (
torch.LongTensor
,形狀為(batch_size, sequence_length)
, 可選) — 每個輸入序列 token 在位置嵌入中的位置索引。選擇範圍為[0, config.n_positions - 1]
。 - past_key_values (
list[torch.FloatTensor]
, 可選) — 預先計算的隱藏狀態(自注意力塊和交叉注意力塊中的鍵和值),可用於加速順序解碼。這通常包括模型在解碼前期返回的past_key_values
,當use_cache=True
或config.use_cache=True
時。允許兩種格式:
- 一個 Cache 例項,請參閱我們的 kv cache 指南;
- 長度為
config.n_layers
的tuple(torch.FloatTensor)
元組,每個元組包含 2 個形狀為(batch_size, num_heads, sequence_length, embed_size_per_head)
的張量)。這也被稱為傳統快取格式。
模型將輸出與作為輸入提供的快取格式相同的快取格式。如果沒有傳遞
past_key_values
,將返回傳統快取格式。如果使用了
past_key_values
,使用者可以選擇只輸入最後一個input_ids
(那些沒有將其過去鍵值狀態提供給此模型的)的形狀(batch_size, 1)
,而不是所有input_ids
的形狀(batch_size, sequence_length)
。 - 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
的 token 將被忽略(掩碼),損失只對標籤在[0, ..., config.vocab_size]
範圍內的 token 計算。 - 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)
, 可選) — 描述輸入序列 token 在序列中位置的索引。與position_ids
不同,此張量不受填充影響。它用於在正確位置更新快取並推斷完整的序列長度。 - logits_to_keep (
Union[int, torch.Tensor]
, 預設為0
) — 如果是int
,則計算最後logits_to_keep
個 token 的對數。如果是0
,則計算所有input_ids
的對數(特殊情況)。生成時只需要最後一個 token 的對數,只計算該 token 可以節省記憶體,這對於長序列或大詞彙量來說非常顯著。如果是torch.Tensor
,則必須是 1D,對應於序列長度維度中要保留的索引。這在使用打包張量格式(批次和序列長度的單一維度)時很有用。
返回
transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
或 tuple(torch.FloatTensor)
一個 transformers.models.video_llava.modeling_video_llava.VideoLlavaCausalLMOutputWithPast
或一個 torch.FloatTensor
的元組(如果傳遞了 return_dict=False
或 config.return_dict=False
),包含根據配置 (VideoLlavaConfig) 和輸入而定的各種元素。
-
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=True
或當config.use_cache=True
時返回) —config.n_layers
長度的tuple(torch.FloatTensor)
元組,每個元組包含 2 個形狀為(batch_size, num_heads, sequence_length, embed_size_per_head)
的張量)包含預計算的隱藏狀態(自注意力塊中的鍵和值),可用於(參見
past_key_values
輸入)加速順序解碼。 -
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_hidden_states (
torch.FloatTensor
, 可選) — 形狀為 (batch_size, num_images, sequence_length, hidden_size) 的torch.FloatTensor
。由視覺編碼器生成並投影最後隱藏狀態後的模型影像隱藏狀態。 -
video_hidden_states (
torch.FloatTensor
, 可選) — 形狀為(batch_size * num_frames, num_videos, sequence_length, hidden_size)
的torch.FloatTensor
。由視覺編碼器生成並投影最後隱藏狀態後的模型影片隱藏狀態。
VideoLlavaForConditionalGeneration 的前向方法,覆蓋了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但在此之後應該呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。
示例
>>> from PIL import Image
>>> import requests
>>> 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"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> 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']