Transformers documentation
Video-LLaVA
该模型于 2023-11-16 在 HF papers 上发布,并于 2024-05-15 贡献至 Hugging Face Transformers。
Video-LLaVA
概述
Video-LLaVa 是一个开源的多模态 LLM,通过在 Llava1.5 和 VideChat 生成的多模态指令跟随数据上对 LlamA/Vicuna 进行微调而训练得到。它是一个基于 transformer 架构的自回归语言模型。Video-LLaVa 将视觉表示统一到语言特征空间,使 LLM 能够同时对图像和视频执行视觉推理。
Video-LLaVA 模型由 Bin Lin、Yang Ye、Bin Zhu、Jiaxi Cui、Munang Ning、Peng Jin 和 Li Yuan 在 Video-LLaVA: Learning United Visual Representation by Alignment Before Projection 中提出。
该论文的摘要如下:
大型视觉-语言模型(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 贡献。 原始代码可在 此处 找到。
在 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}}发出警告。如果您拥有该模型检查点,强烈建议为 processor 添加这些属性;如果模型不属于您,则建议提交一个 PR。 添加这些属性意味着 LLaVA 将尝试推断每张图像所需的图像 token 数量,并根据 token 数量在文本中扩展相应数量的<image>占位符。通常每张图像大约需要 500 个 token,因此请确保文本未被截断,否则在合并 embeddings 时将会失败。 这些属性可以从模型配置中获取,例如model.config.vision_config.patch_size或model.config.vision_feature_select_strategy。如果视觉骨干网络添加了 CLS token,num_additional_image_tokens应为1;如果未向视觉 patches 添加任何额外内容,则应为0。
使用示例
单一媒体模式
该模型可以接受图像和视频作为输入。以下是在半精度(torch.float16)下进行推理的示例代码:
import av
import numpy as np
from transformers import VideoLlavaForConditionalGeneration, VideoLlavaProcessor
def read_video_pyav(container, indices):
'''
Decode the video with PyAV decoder.
Args:
container (`av.container.input.InputContainer`): PyAV container.
indices (`list[int]`): List of frame indices to decode.
Returns:
result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
'''
frames = []
container.seek(0)
start_index = indices[0]
end_index = indices[-1]
for i, frame in enumerate(container.decode(video=0)):
if i > end_index:
break
if i >= start_index and i in indices:
frames.append(frame)
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
# Load the model in half-precision
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", device_map="auto")
processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
# Load the video as an np.array, sampling uniformly 8 frames
video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
container = av.open(video_path)
total_frames = container.streams.video[0].frames
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
video = read_video_pyav(container, indices)
# For better results, we recommend to prompt the model in the following format
prompt = "USER: <video>\nWhy is this funny? ASSISTANT:"
inputs = processor(text=prompt, videos=video, return_tensors="pt").to(model.device)
out = model.generate(**inputs, max_new_tokens=60)
processor.batch_decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)对于多轮对话,请将提示格式更改为:
"USER: <video>\nWhat do you see in this video? ASSISTANT: A baby reading a book. USER: Why is the it funny? ASSISTANT:"混合媒体模式
该模型还可以从交错的图像-视频输入中生成内容。但请注意,它并非在交错的图像-视频设置下训练的,这可能会影响性能。以下是混合媒体输入的使用示例,请在上述代码片段中添加以下行:
import requests
from PIL import Image
# Generate from image and video mixed inputs
# Load and image and write a new prompt
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
prompt = "USER: <image>\nHow many cats are there in the image? ASSISTANT: There are two cats. USER: <video>\nWhy is this video funny? ASSISTANT:"
inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt").to(model.device)
# Generate
generate_ids = model.generate(**inputs, max_length=50)
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)模型优化
使用 Bitsandbytes 进行量化以实现内存效率
模型可以以更低的位宽加载,在保持原始模型性能的同时显著降低内存占用,从而实现在资源受限场景下的高效部署。
首先,请通过运行 pip install bitsandbytes 安装 bitsandbytes,并确保您拥有该库支持的 GPU/加速器。
bitsandbytes 正在重构以支持 CUDA 之外的多种后端。目前,ROCm(AMD GPU)和 Intel CPU 的实现已趋于成熟,Intel XPU 正在开发中,预计将在第四季度/第一季度支持 Apple Silicon。有关安装说明和最新的后端更新,请访问 此链接。
我们非常重视您的反馈,以便在正式发布前发现并修复问题!请查阅这些文档以获取更多详情和反馈链接。
只需按照下图所示添加 BitsAndBytesConfig,即可加载量化模型:
from transformers import BitsAndBytesConfig, VideoLlavaForConditionalGeneration
# specify how to quantize the model
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
)
model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", quantization_config=quantization_config, device_map="auto")使用 Flash-Attention 2 加速生成
此外,通过使用 Flash Attention,我们可以大幅加快模型推理速度。Flash Attention 是模型内部所用注意力机制的一种更快实现。
首先,请确保安装最新版本的 Flash Attention 2:
pip install -U flash-attn --no-build-isolation
此外,您的硬件必须与 Flash-Attention 2 兼容。有关详细信息,请参阅 flash attention 仓库 的官方文档。只有当模型以 torch.float16 或 torch.bfloat16 加载时,才能使用 FlashAttention-2。
要使用 Flash Attention-2 加载并运行模型,只需在加载模型时添加 attn_implementation="flash_attention_2",如下所示:
from transformers import VideoLlavaForConditionalGeneration
model = VideoLlavaForConditionalGeneration.from_pretrained(
"LanguageBind/Video-LLaVA-7B-hf", ,
attn_implementation="flash_attention_2",
).to(0, device_map="auto")VideoLlavaConfig
class transformers.VideoLlavaConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_index: int = 32000video_token_index: int = 32001projector_hidden_act: str = 'gelu'vision_feature_select_strategy: typing.Literal['default', 'full'] = 'default'vision_feature_layer: int | list[int] = -2image_seq_length: int = 256video_seq_length: int = 2056multimodal_projector_bias: bool = Truetie_word_embeddings: bool = False )
参数
- vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。 - text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - image_token_index (
int,可选,默认为32000) — 用作输入图像占位符的图像 token 索引。 - video_token_index (
int,可选,默认为32001) — 用作输入视频占位符的视频 token 索引。 - projector_hidden_act (
str, 可选, 默认为gelu) — 多模态投影器使用的激活函数。 - vision_feature_select_strategy (
Literal[default, full],可选,默认为default) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 - vision_feature_layer (
Union[int, list[int]],可选,默认为-2) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引处的视觉特征拼接起来,以构成视觉特征。 - image_seq_length (
int,可选,默认为256) — 单个图像嵌入的序列长度。 - video_seq_length (
int,可选,默认为2056) — 单个视频嵌入的序列长度。 - multimodal_projector_bias (
bool,可选,默认为True) — 是否在多模态投影器中使用偏置。 - tie_word_embeddings (
bool,可选,默认为False) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 VideoLlavaModel 配置的类。它根据指定的参数实例化 Video Llava 模型,并定义模型架构。使用默认值实例化配置,将得到与 LanguageBind/Video-LLaVA-7B-hf 类似的配置。
配置对象继承自 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.configVideoLlavaImageProcessor
class transformers.VideoLlavaImageProcessor
< source >( do_resize: bool = Truesize: dict[str, int] | None = Noneresample: Resampling = <Resampling.BICUBIC: 3>do_center_crop: bool = Truecrop_size: dict[str, int] | None = Nonedo_rescale: bool = Truerescale_factor: int | float = 0.00392156862745098do_normalize: bool = Trueimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonedo_convert_rgb: bool = True**kwargs )
参数
- do_resize (
bool,可选,默认为True) — 是否将图像的 (height, width) 维度调整为指定的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 图像处理器。
预处理
< source >( images: list[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]] | None = Nonedo_resize: bool | None = Nonesize: dict[str, int] | None = Noneresample: PIL.Image.Resampling | None = Nonedo_center_crop: bool | None = Nonecrop_size: int | None = Nonedo_rescale: bool | None = Nonerescale_factor: float | None = Nonedo_normalize: bool | None = Noneimage_mean: float | list[float] | None = Noneimage_std: float | list[float] | None = Nonedo_convert_rgb: bool | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = Nonedata_format: transformers.image_utils.ChannelDimension | None = <ChannelDimension.FIRST: 'channels_first'>input_data_format: str | transformers.image_utils.ChannelDimension | None = Nonereturn_legacy_image_output: bool = True )
参数
- images (
ImageInput,可选) — 要预处理的图像列表。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_resize (
bool,可选,默认为self.do_resize) — 是否调整图像大小。 - size (
dict[str, int], 可选,默认为self.size) — 调整大小后图像的尺寸。图像的最短边会被调整为 size[“shortest_edge”],最长边则按比例调整以保持输入的宽高比。 - resample (
int,可选,默认为self.resample) — 在对图像进行缩放时使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_center_crop (
bool,可选,默认为self.do_center_crop) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int],可选,默认为self.crop_size) — 中心裁剪的大小。仅当do_center_crop设置为True时生效。 - do_rescale (
bool,可选,默认为self.do_rescale) — 是否对图像进行重新缩放。 - rescale_factor (
float,可选,默认为self.rescale_factor) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,可选,默认为self.do_normalize) — 是否对图像进行归一化。 - image_mean(
float或list[float],可选,默认为self.image_mean)— 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
float或list[float],可选,默认为self.image_std) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_convert_rgb (
bool,可选,默认为self.do_convert_rgb) — 是否将图像转换为 RGB。 - return_tensors (
str或TensorType, 可选) — 要返回的张量类型。可以是以下之一:- Unset:返回一个
np.ndarray列表。 TensorType.PYTORCH或'pt':返回类型为torch.Tensor的批次。TensorType.NUMPY或'np':返回类型为np.ndarray的批次。
- Unset:返回一个
- data_format (
ChannelDimension或str, 可选, 默认为ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。- Unset:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension或str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
预处理一张图像或一批图像。
VideoLlavaVideoProcessor
class transformers.VideoLlavaVideoProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.VideosKwargs'> )
参数
- 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 为 int 时,是否在调整大小时默认使用正方形图像。 - 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':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (VideosKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
构建一个 VideoLlavaVideoProcessor 视频处理器。
VideoLlavaProcessor
类 transformers.VideoLlavaProcessor
< source >( image_processor = Nonevideo_processor = Nonetokenizer = Nonepatch_size = 14vision_feature_select_strategy = 'default'image_token = '<image>'video_token = '<video>'chat_template = Nonenum_additional_image_tokens = 1**kwargs )
参数
- image_processor (
VideoLlavaImageProcessor) — 图像处理器是必需的输入。 - video_processor (
VideoLlavaVideoProcessor) — 视频处理器是必需的输入。 - tokenizer (
tokenizer_class) — 分词器是必需的输入。 - patch_size (
int,可选,默认为 14) — 视觉塔的 patch 大小。 - vision_feature_select_strategy (
str, 可选,默认为"default") — 用于从视觉骨干网络中选择视觉特征的特征选择策略。应与模型配置中的设置保持一致。 - image_token (
str,可选,默认为"<image>") — 用于表示图像位置的专用标记。 - video_token (
str,可选,默认为"<video>") — 用于表示视频位置的专用标记。 - chat_template (
str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。 - num_additional_image_tokens (
int,可选,默认为 1) — 添加到图像嵌入中的额外 token 数量,例如 CLS(+1)。如果主干网络没有附加 CLS 或其他额外 token,则无需设置此参数。
构建一个 VideoLlavaProcessor,它将图像处理器、视频处理器和分词器封装为单一处理器。
VideoLlavaProcessor 提供了 VideoLlavaImageProcessor、VideoLlavaVideoProcessor 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~VideoLlavaImageProcessor、~VideoLlavaVideoProcessor 和 ~tokenizer_class。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - text (
Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True,以避免与批量输入产生歧义。 - videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - audio (
Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
VideoLlavaModel
class transformers.VideoLlavaModel
< source >( config: VideoLlavaConfig )
参数
- config (VideoLlavaConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
由视觉骨干网络和语言模型组成的 VideoLlava 模型,不包含语言建模头。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonevision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'> ) → VideoLlavaModelOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor,可选) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - pixel_values_videos (
torch.Tensor,形状为(batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用video_processor_class获取视频的像素值。有关详细信息,请参阅video_processor_class.__call__(processor_class使用video_processor_class来处理视频)。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - vision_feature_layer (
Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。 - vision_feature_select_strategy (
str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"或"full"之一。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
VideoLlavaModelOutputWithPast 或 tuple(torch.Tensor)
VideoLlavaModelOutputWithPast 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
VideoLlavaModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选)— 模型最后一层输出的隐藏状态序列。past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。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 之后的权重,用于在自注意力头中计算加权平均值。
image_hidden_states (
torch.Tensor,可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的torch.Tensor`。 由视觉编码器生成并在投影最后一个隐藏状态后得到的模型的 image_hidden_states。video_hidden_states (
torch.Tensor,可选) — 一个尺寸为(batch_size * num_frames, num_videos, sequence_length, hidden_size)的torch.Tensor。 由视觉编码器生成的模型 video_hidden_states,并在投影最后一个隐藏状态之后得到。
get_image_features
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_images: typing.Optional[torch.Tensor] = Nonevision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor,可选) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - pixel_values_images (
torch.Tensor,形状为(batch_size, channels, height, width)) — 与输入图像对应的张量。 - vision_feature_select_strategy (
str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"或"full" - vision_feature_layer (
Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。 - vision_feature_select_strategy (
str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"或"full"之一。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
从视觉塔获取图像的最后隐藏状态,并应用多模态投影。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 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
< source >( input_ids: LongTensorinputs_embeds: Tensorimage_features: typing.Optional[torch.Tensor] = Nonevideo_features: typing.Optional[torch.Tensor] = None )
从 input_ids 或 inputs_embeds 中获取多模态占位符掩码,并检查占位符 token 的数量是否等于多模态特征的长度。如果长度不一致,则会引发错误。
get_video_features
< source >( pixel_values_videos: Tensorvision_feature_layer: int | list[int] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values_videos (
torch.Tensor,形状为(batch_size, num_frames, num_channels, frame_size, frame_size)) — 与输入视频对应的张量。可以使用 VideoLlavaVideoProcessor 获取视频的像素值。有关详细信息,请参阅 VideoLlavaVideoProcessor.call()(VideoLlavaProcessor 使用 VideoLlavaVideoProcessor 来处理视频)。 - vision_feature_layer (
Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VideoLlavaConfig)和输入。
从视觉塔获取视频的最后隐藏状态,并应用多模态投影。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
VideoLlavaForConditionalGeneration
类 transformers.VideoLlavaForConditionalGeneration
< source >( config: VideoLlavaConfig )
参数
- config (VideoLlavaConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
由视觉骨干网络和语言模型组成的 VideoLlava 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_images: typing.Optional[torch.Tensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonevision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VideoLlavaCausalLMOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor,可选) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - pixel_values_images (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size)) -- The tensors corresponding to the input images. Pixel values can be obtained using [AutoImageProcessor](/docs/transformers/main/en/model_doc/auto#transformers.AutoImageProcessor). See [VideoLlavaImageProcessor.__call__()](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) for details ([]LlavaProcessor`] uses VideoLlavaImageProcessor for processing images). - pixel_values_videos (
torch.Tensor,形状为(batch_size, num_frames, num_channels, frame_size, frame_size),可选) — 对应输入视频的张量。可以使用video_processor_class获取视频的像素值。有关详细信息,请参阅video_processor_class.__call__(processor_class使用video_processor_class来处理视频)。 - attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- position_ids (
torch.LongTensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由past_key_values在解码的先前阶段返回,当use_cache=True或config.use_cache=True.仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入
past_key_values,则默认会初始化 DynamicCache。模型将输出与输入相同的缓存格式。
如果使用了
past_key_values,用户应仅输入未处理的input_ids(即未向该模型提供其过去键值状态的那些),其形状为(batch_size, unprocessed_length),而不是形状为(batch_size, sequence_length)的全部input_ids。 - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入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,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。 - logits_to_keep (
Union[int, torch.Tensor], 可选,默认为0) — 如果为int,则计算最后logits_to_keep个 token 的 logits。如果为0,则计算所有input_ids的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
VideoLlavaCausalLMOutputWithPast 或 tuple(torch.Tensor)
VideoLlavaCausalLMOutputWithPast 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(None)和输入。
VideoLlavaForConditionalGeneration 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 语言建模损失(用于下一个 token 预测)。logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。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 之后的权重,用于在自注意力头中计算加权平均值。
image_hidden_states (
torch.Tensor,可选) — 大小为 (batch_size, num_images, sequence_length, hidden_size) 的torch.Tensor`。 由视觉编码器生成并在投影最后一个隐藏状态后得到的模型的 image_hidden_states。video_hidden_states (
torch.Tensor,可选) — 一个尺寸为(batch_size * num_frames, num_videos, sequence_length, hidden_size)的torch.Tensor。 由视觉编码器生成的模型 video_hidden_states,并在投影最后一个隐藏状态之后得到。
示例:
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import numpy as np
>>> import av
>>> from huggingface_hub import hf_hub_download
>>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
>>> def read_video_pyav(container, indices):
... '''
... Decode the video with PyAV decoder.
... Args:
... container (`av.container.input.InputContainer`): PyAV container.
... indices (`list[int]`): List of frame indices to decode.
... Returns:
... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
... '''
... frames = []
... container.seek(0)
... start_index = indices[0]
... end_index = indices[-1]
... for i, frame in enumerate(container.decode(video=0)):
... if i > end_index:
... break
... if i >= start_index and i in indices:
... frames.append(frame)
... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
>>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
>>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
>>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
>>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
>>> container = av.open(video_path)
>>> # sample uniformly 8 frames from the video
>>> total_frames = container.streams.video[0].frames
>>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)
>>> clip = read_video_pyav(container, indices)
>>> inputs = processor(text=prompt, videos=clip, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=80)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"USER: Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.Ъ. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a"
>>> # to generate from image and video mix
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> prompt = [
... "USER: <image>\nHow many cats do you see? ASSISTANT:",
... "USER: <video>\nWhy is this video funny? ASSISTANT:"
... ]
>>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_length=50)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
['USER: How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER: Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.Ъ. The baby is holding the remote']get_image_features
< source >( pixel_values: Tensorvision_feature_layer: int | list[int] | None = Nonevision_feature_select_strategy: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 对应于输入图像的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - vision_feature_layer (
Union[int, list[int]], 可选) — 用于选择视觉特征的层索引。如果提供了多个索引,则会将对应索引的视觉特征拼接起来,以形成视觉特征。 - vision_feature_select_strategy (
str, 可选) — 用于从视觉主干网络中选择视觉特征的特征选择策略。 可以是"default"或"full"
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 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 之后的权重,用于在自注意力头中计算加权平均值。