Transformers documentation

V-JEPA 2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2025-06-11 在 HF papers 上发布,并于 2025-06-11 贡献至 Hugging Face Transformers。

SDPA FlashAttention

V-JEPA 2

V-JEPA 2(博客文章)是由 Meta 的 FAIR 开发的一种用于训练视频编码器的自监督方法。利用互联网规模的视频数据,V-JEPA 2 在运动理解和人类动作预测任务上达到了最先进的性能。V-JEPA 2-AC 是一个潜在动作条件世界模型,它基于 V-JEPA 2 进行后训练(使用少量机器人轨迹交互数据),无需针对特定环境的数据采集、特定任务的训练或校准,即可解决机器人操作任务。

drawing

您可以在 V-JEPA 2 集合中找到所有原始的 V-JEPA2 检查点。

该模型由 koustuvs、yonigozlan 和 qubvel 贡献。原始代码可在此处找到。

使用示例

以下代码片段展示了如何使用 AutoModel 类加载 V-JEPA 2 模型以进行特征提取。

import numpy as np
from torchcodec.decoders import VideoDecoder


processor = AutoVideoProcessor.from_pretrained("facebook/vjepa2-vitl-fpc64-256")
model = AutoModel.from_pretrained(
    "facebook/vjepa2-vitl-fpc64-256",
    device_map="auto",
    attn_implementation="sdpa"
)

video_url = "https://huggingface.co/datasets/nateraw/kinetics-mini/resolve/main/val/archery/-Qz25rXdMjE_000014_000024.mp4"

vr = VideoDecoder(video_url)
frame_idx = np.arange(0, 64) # choosing some frames. here, you can define more complex sampling strategy
video = vr.get_frames_at(indices=frame_idx).data  # T x C x H x W
video = processor(video, return_tensors="pt").to(model.device)
outputs = model(**video)

# V-JEPA 2 encoder outputs, same as calling `model.get_vision_features()`
encoder_outputs = outputs.last_hidden_state

# V-JEPA 2 predictor outputs
predictor_outputs = outputs.predictor_output.last_hidden_state

V-JEPA 2 还可以针对视频分类任务进行微调。在下面的代码片段中,我们展示了如何使用在 Something-Something-V2 视频分类数据集上微调后的模型。

import numpy as np
import torch
from torchcodec.decoders import VideoDecoder

from transformers import AutoModelForVideoClassification, AutoVideoProcessor


# Load model and video preprocessor
hf_repo = "facebook/vjepa2-vitl-fpc16-256-ssv2"

model = AutoModelForVideoClassification.from_pretrained(hf_repo, device_map="auto")
processor = AutoVideoProcessor.from_pretrained(hf_repo)

# To load a video, sample the number of frames according to the model.
video_url = "https://huggingface.co/datasets/nateraw/kinetics-mini/resolve/main/val/bowling/-WH-lxmGJVY_000005_000015.mp4"
vr = VideoDecoder(video_url)
frame_idx = np.arange(0, model.config.frames_per_clip, 8) # you can define more complex sampling strategy
video = vr.get_frames_at(indices=frame_idx).data  # frames x channels x height x width

# Preprocess and run inference
inputs = processor(video, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)
logits = outputs.logits

print("Top 5 predicted class names:")
top5_indices = logits.topk(5).indices[0]
top5_probs = torch.softmax(logits, dim=-1).topk(5).values[0]
for idx, prob in zip(top5_indices, top5_probs):
    text_label = model.config.id2label[idx.item()]
    print(f" - {text_label}: {prob:.2f}")

VJEPA2Config

class transformers.VJEPA2Config

< >

( 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 = Nonepatch_size: int | list[int] | tuple[int, int] = 16crop_size: int = 256frames_per_clip: int = 64tubelet_size: int = 2hidden_size: int = 1024in_chans: int = 3num_attention_heads: int = 16num_hidden_layers: int = 24drop_path_rate: float | int = 0.0mlp_ratio: int | float = 4.0layer_norm_eps: float = 1e-06qkv_bias: bool = Trueattention_probs_dropout_prob: float | int = 0.0hidden_act: str = 'gelu'initializer_range: float = 0.02attention_dropout: float | int = 0.0num_pooler_layers: int = 3pred_hidden_size: int = 384pred_num_attention_heads: int = 12pred_num_hidden_layers: int = 12pred_num_mask_tokens: int = 10pred_zero_init_mask_tokens: bool = Truepred_mlp_ratio: int | float = 4.0 )

参数

  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • crop_size (int,可选,默认为 256) — 模型的输入分辨率
  • frames_per_clip (int,可选,默认为 64) — 模型预训练时使用的帧数。不影响推理。
  • tubelet_size (int,可选,默认为 2) — 用于单个 rastor 的时间帧数量,更多信息请参阅论文。
  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • in_chans (int,可选,默认为 3) — 输入通道数。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_hidden_layers (int,可选,默认为 24) — Transformer 解码器中的隐藏层数量。
  • drop_path_rate (Union[float, int],可选,默认为 0.0) — 用于 patch fusion 的 drop path 比率。
  • mlp_ratio (Union[int, float],可选,默认为 4.0) — MLP 隐藏层维度与嵌入维度的比值。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • num_pooler_layers (int,可选,默认为 3) — 池化器中自注意力层的数量。
  • pred_hidden_size (int,可选,默认为 384) — 预测器层的维度
  • pred_num_attention_heads (int,可选,默认为 12) — Predictor 中每个注意力层的注意力头数量
  • pred_num_hidden_layers (int,可选,默认为 12) — Predictor 中的隐藏层数量
  • pred_num_mask_tokens (int,可选,默认为 10) — 定义 Predictor 中使用的 mask token 数量
  • pred_zero_init_mask_tokens (bool,可选,默认为 True) — 在预测器中将 mask token 初始化为 0。
  • pred_mlp_ratio (float,可选,默认值为 4.0) — Predictor 中使用的 MLP 的隐藏层大小与 pred_hidden_size 的比值。

这是用于存储 VJEPA2Model 配置的类。它根据指定的参数实例化 Vjepa2 模型,并定义模型架构。使用默认值实例化配置,将得到与 facebook/vjepa2-vitl-fpc64-256 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import VJEPA2Config, VJEPA2Model

>>> # Initializing a VJEPA2 vjepa2-vitl-fpc64-256 style configuration
>>> configuration = VJEPA2Config()

>>> # Initializing a model (with random weights) from the vjepa2-vitl-fpc64-256  style configuration
>>> model = VJEPA2Model(configuration)

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

VJEPA2Model

class transformers.VJEPA2Model

< >

( config: VJEPA2Config )

参数

  • config (VJEPA2Config) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

未添加任何特定头部的裸 Vjepa2 模型,直接输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values_videos: Tensorcontext_mask: list[torch.Tensor] | None = Nonetarget_mask: list[torch.Tensor] | None = Noneskip_predictor: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VJEPA2WithMaskedInputModelOutput or tuple(torch.Tensor)

参数

  • pixel_values_videos(形状为 (batch_size, num_frames, num_channels, frame_size, frame_size) 的 torch.Tensor)— 对应输入视频的张量。可以使用 VJEPA2VideoProcessor 获取视频的像素值。有关详细信息,请参阅 VJEPA2VideoProcessor.call()(processor_class 使用 VJEPA2VideoProcessor 处理视频)。
  • context_mask (torch.Tensor,形状为 [batch_size, patch_size, 1],可选) — 指示哪些编码器输出 patch 将暴露给预测器的掩码位置 ID。 默认情况下,该掩码通过 torch.arange(N).unsqueeze(0).repeat(B,1) 创建,表示预测器可访问完整的上下文。
  • target_mask (torch.Tensor,形状为 [batch_size, patch_size, 1],可选) — 指示哪些编码器输出 patch 将被用作预测器预测目标的掩码位置 ID。默认情况下,该掩码通过 torch.arange(N).unsqueeze(0).repeat(B,1) 创建,表示预测器应预测所有编码器 patch。
  • skip_predictor (bool,可选,默认为 False) — 用于跳过 predictor 前向传播的标志,适用于只需要编码器输出的场景

返回值

VJEPA2WithMaskedInputModelOutput 或 tuple(torch.Tensor)

VJEPA2WithMaskedInputModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(VJEPA2Config)和输入。

VJEPA2Model 的 forward 方法会重写 __call__ 特殊方法。

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

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • masked_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选,当提供应用于 VJEPA2Encoder 输出的 context_mask 时返回) — 模型的带掩码隐藏状态。

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

  • predictor_output(VJEPA2WithMaskedInputPredictorOutput,可选)— Predictor 模块的输出。

VJEPA2ForVideoClassification

class transformers.VJEPA2ForVideoClassification

< >

( config: VJEPA2Config )

参数

  • config (VJEPA2Config) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

V-JEPA 2 模型,在顶部添加了一个视频分类头(一个位于注意力池化器之上的线性层)。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values_videos: Tensorlabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → ImageClassifierOutput or tuple(torch.Tensor)

参数

  • pixel_values_videos(形状为 (batch_size, num_frames, num_channels, frame_size, frame_size) 的 torch.Tensor)— 对应输入视频的张量。可以使用 VJEPA2VideoProcessor 获取视频的像素值。有关详细信息,请参阅 VJEPA2VideoProcessor.call()(processor_class 使用 VJEPA2VideoProcessor 处理视频)。
  • labels(形状为 (batch_size,) 的 torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回值

ImageClassifierOutput 或 tuple(torch.Tensor)

一个 ImageClassifierOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(VJEPA2Config)和输入。

VJEPA2ForVideoClassification 的 forward 方法会重写 __call__ 特殊方法。

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • logits(形状为 (batch_size, config.num_labels) 的 torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。

  • 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, patch_size, sequence_length)。

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

示例:

>>> import torch
>>> import numpy as np
>>> from transformers import AutoVideoProcessor, VJEPA2ForVideoClassification

>>> device = "cuda"

>>> video_processor = AutoVideoProcessor.from_pretrained("facebook/vjepa2-vitl-fpc16-256-ssv2")
>>> model = VJEPA2ForVideoClassification.from_pretrained("facebook/vjepa2-vitl-fpc16-256-ssv2").to(device)

>>> video = np.ones((64, 256, 256, 3))  # 64 frames, 256x256 RGB
>>> inputs = video_processor(video, return_tensors="pt").to(device)

>>> # For inference
>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> logits = outputs.logits

>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])

>>> # For training
>>> labels = torch.ones(1, dtype=torch.long, device=device)
>>> loss = model(**inputs, labels=labels).loss

VJEPA2VideoProcessor

class transformers.VJEPA2VideoProcessor

< >

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

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'shortest_edge' -- 292}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 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.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当 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,默认为 256) — 应用 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, 可选) — 是否在处理前对视频进行帧采样,还是处理整个视频。
  • video_metadata (Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。
  • fps (Annotated[int | float | None, None], kwargs) — 当 do_sample_frames=True 时,每秒要采样的目标帧数。
  • num_frames (Annotated[int | None, None], kwargs) — 当 do_sample_frames=True 时,要采样的最大帧数。
  • return_metadata (bool,kwargs,可选,默认为 False) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (VideosKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

构建一个 VJEPA2VideoProcessor 视频处理器。

Update on GitHub