Transformers documentation
VidEoMT
该模型于 2026-02-19 在 HF papers 上发布,并于 2026-03-25 贡献至 Hugging Face Transformers。
VidEoMT
概述
VidEoMT 模型由 Narges Norouzi、Idil Esen Zulfikar、Niccolò Cavagnero、Tommie Kerssies、Bastian Leibe、Gijs Dubbelman 和 Daan de Geus 在 Your ViT is Secretly Also a Video Segmentation Model 中提出。Video Encoder-only Mask Transformer (VidEoMT) 是一个用于在线视频分割的轻量级纯编码器模型,基于普通的 Vision Transformer (ViT) 构建。它是 EoMT 在视频领域的最小化扩展,在 ViT 编码器内部同时执行空间和时间推理,无需依赖专门的跟踪模块或繁重的任务特定头部。
该论文的摘要如下:
现有的在线视频分割模型通常将逐帧分割器与复杂的专用跟踪模块相结合。虽然有效,但这些模块引入了显著的架构复杂性和计算开销。近期的研究表明,当具备足够的容量并经过大规模预训练时,普通的 Vision Transformer (ViT) 编码器无需专用模块即可执行准确的图像分割。受此观察启发,我们提出了 Video Encoder-only Mask Transformer (VidEoMT),这是一种简单的仅编码器视频分割模型,消除了对专用跟踪模块的需求。为了在仅编码器的 ViT 中实现时序建模,VidEoMT 引入了一种轻量级的查询传播机制,通过复用前一帧的查询来跨帧传递信息。为了在适应新内容方面取得平衡,它采用了一种查询融合策略,将传播的查询与一组时序无关的学习查询相结合。因此,VidEoMT 在不增加复杂性的情况下获得了跟踪器的优势,在保持具有竞争力的准确率的同时,速度提升了 5 倍至 10 倍,使用 ViT-L 骨干网络时运行速度最高可达 160 FPS。
提示:
- VidEoMT 目前仅支持带有 register tokens 的 DINOv2 主干网络。可用的模型尺寸为 ViT-S、ViT-B 和 ViT-L。
- 该模型接受形状为
(batch_size, num_frames, 3, height, width)的 5D 张量作为视频输入。 - VidEoMT 支持三种视频分割任务:实例、语义和全景分割,每种任务在视频处理器上都有专用的后处理方法。
架构信息
VidEoMT 基于 EoMT 构建,后者将带有 register tokens 的普通 DINOv2 预训练 Vision Transformer 重新用作分割模型。EoMT 在 ViT 编码器内部直接引入了可学习的 object queries 和一个轻量级的 mask prediction head,从而无需使用任务特定的解码器。
VidEoMT 通过以下两个关键扩展将其应用于视频:
- 查询传播:来自上一帧的对象查询通过线性投影(
query_updater)传递到下一帧,从而无需专用跟踪器即可实现时序推理。 - 查询融合:将传播的查询与一组与时间无关的学习查询相加,使模型能够适应视频中出现的新的对象。
早期的编码器层独立(并行)处理所有帧,而最后的块则针对每一帧使用融合后的查询进行操作,从而生成逐帧的掩码和类别预测。
使用示例
使用 Hugging Face 的 VidEoMT 实现,配合预训练模型进行推理。以下示例复用公开的 tue-mps/videomt-dinov2-small-ytvis2019 检查点,以演示在示例视频上执行视频实例、语义和全景后处理。
视频实例分割
import matplotlib.pyplot as plt
import numpy as np
import torch
from transformers import AutoModelForUniversalSegmentation, AutoVideoProcessor
from transformers.video_utils import load_video
model_id = "tue-mps/videomt-dinov2-small-ytvis2019"
processor = AutoVideoProcessor.from_pretrained(model_id)
model = AutoModelForUniversalSegmentation.from_pretrained(model_id, device_map="auto")
video_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/videos/pexels-allan-mas-5362370.mp4"
# Sample 8 frames to keep the example lightweight.
video_frames, _ = load_video(video_url, num_frames=8)
inputs = processor(videos=[video_frames], return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
original_height, original_width = video_frames[0].shape[:2]
target_sizes = [(original_height, original_width)] * len(video_frames)
results = processor.post_process_instance_segmentation(
outputs,
target_sizes=target_sizes,
)
fig, axes = plt.subplots(2, 4, figsize=(16, 8))
for idx, (ax, frame, result) in enumerate(zip(axes.flatten(), video_frames, results)):
ax.imshow(frame)
seg = result["segmentation"].cpu().numpy()
masked = np.ma.masked_where(seg == -1, seg)
ax.imshow(masked, alpha=0.6, cmap="tab20")
ax.set_title(f"Frame {idx}")
ax.axis("off")
plt.suptitle("Video Instance Segmentation")
plt.tight_layout()
plt.show()视频语义分割
import matplotlib.pyplot as plt
import torch
from transformers import AutoModelForUniversalSegmentation, AutoVideoProcessor
from transformers.video_utils import load_video
model_id = "tue-mps/videomt-dinov2-small-ytvis2019"
processor = AutoVideoProcessor.from_pretrained(model_id)
model = AutoModelForUniversalSegmentation.from_pretrained(model_id, device_map="auto")
video_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/videos/pexels-allan-mas-5362370.mp4"
# Sample 8 frames to keep the example lightweight.
video_frames, _ = load_video(video_url, num_frames=8)
inputs = processor(videos=[video_frames], return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
original_height, original_width = video_frames[0].shape[:2]
target_sizes = [(original_height, original_width)] * len(video_frames)
preds = processor.post_process_semantic_segmentation(
outputs,
target_sizes=target_sizes,
)
fig, axes = plt.subplots(2, 4, figsize=(16, 8))
for idx, (ax, frame, seg_map) in enumerate(zip(axes.flatten(), video_frames, preds)):
ax.imshow(frame)
ax.imshow(seg_map.cpu().numpy(), alpha=0.6, cmap="tab20")
ax.set_title(f"Frame {idx}")
ax.axis("off")
plt.suptitle("Video Semantic Segmentation")
plt.tight_layout()
plt.show()视频全景分割
import matplotlib.pyplot as plt
import numpy as np
import torch
from transformers import AutoModelForUniversalSegmentation, AutoVideoProcessor
from transformers.video_utils import load_video
model_id = "tue-mps/videomt-dinov2-small-ytvis2019"
processor = AutoVideoProcessor.from_pretrained(model_id)
model = AutoModelForUniversalSegmentation.from_pretrained(model_id, device_map="auto")
video_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/videos/pexels-allan-mas-5362370.mp4"
# Sample 8 frames to keep the example lightweight.
video_frames, _ = load_video(video_url, num_frames=8)
inputs = processor(videos=[video_frames], return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
original_height, original_width = video_frames[0].shape[:2]
target_sizes = [(original_height, original_width)] * len(video_frames)
results = processor.post_process_panoptic_segmentation(
outputs,
target_sizes=target_sizes,
)
fig, axes = plt.subplots(2, 4, figsize=(16, 8))
for idx, (ax, frame, result) in enumerate(zip(axes.flatten(), video_frames, results)):
ax.imshow(frame)
seg = result["segmentation"].cpu().numpy()
masked = np.ma.masked_where(seg == -1, seg)
ax.imshow(masked, alpha=0.6, cmap="tab20")
ax.set_title(f"Frame {idx}")
ax.axis("off")
plt.suptitle("Video Panoptic Segmentation")
plt.tight_layout()
plt.show()VideomtVideoProcessor
class transformers.VideomtVideoProcessor
< 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,默认为{'height' -- 640, 'width': 640}): 描述输入到模型的最大尺寸。 - 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,可选,默认为False) — 是否对图像进行中心裁剪。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用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 类。
构建一个 VideomtVideoProcessor 视频处理器。
post_process_semantic_segmentation
< source >( outputstarget_sizes: listreturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (
VideomtForUniversalSegmentationOutput) — 模型的原始输出。 - target_sizes (
list[tuple[int, int]]) —(height, width)元组的列表,对应每个预测所需的最终尺寸。 长度应与输出中的帧数相匹配。 - return_segmentation_scores (
bool,可选,默认为False) — 是否随分割图一起返回分割分数。当True时,返回列表中的每个元素都是一个SemanticSegmentationPostProcessorOutput,包含字段segmentation(类别 ID,形状为(height, width))和segmentation_scores(形状为(num_classes, height, width))。
返回值
list[torch.Tensor] 或 list[SemanticSegmentationPostProcessorOutput]
当 return_segmentation_scores=False(默认值)时,返回一个长度为 batch_size 的列表,其中每个元素都是形状为 (height, width) 的分割图,包含类别 ID。当 return_segmentation_scores=True 时,返回一个 SemanticSegmentationPostProcessorOutput 列表,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。在这两种情况下,(height, width) 均对应目标尺寸。
将 VideomtForUniversalSegmentation 的输出转换为语义分割预测。
post_process_instance_segmentation
< source >( outputstarget_sizes: listthreshold: float = 0.5 ) → list[dict]
参数
- outputs (
VideomtForUniversalSegmentationOutput) — 模型的原始输出。 - target_sizes (
list[tuple[int, int]]) —(height, width)元组的列表,对应每个预测所需的最终尺寸。 长度应与输出中的帧数相匹配。 - threshold (
float,可选,默认值为 0.5) — 保留实例所需的最低综合得分。
返回值
list[dict]
一个字典列表(每帧一个),每个字典包含:
"segmentation"— 形状为(height, width)的torch.Tensor,包含实例 ID(背景为 -1)。"segments_info"— 一个字典列表,每个实例包含"id"、"label_id"和"score"。
将 VideomtForUniversalSegmentation 的输出转换为实例分割预测。
post_process_panoptic_segmentation
< source >( outputstarget_sizes: listthreshold: float = 0.8mask_threshold: float = 0.5overlap_mask_area_threshold: float = 0.8label_ids_to_fuse: set[int] | None = None ) → list[dict]
参数
- outputs (
VideomtForUniversalSegmentationOutput) — 模型的原始输出。 - target_sizes (
list[tuple[int, int]]) —(height, width)元组的列表,对应每个预测所需的最终尺寸。 长度应与输出中的帧数相匹配。 - threshold (
float,可选,默认值为 0.8) — 保留预测片段所需的最低分数。 - mask_threshold (
float,可选,默认值为 0.5) — 用于将掩码概率二值化的阈值。 - overlap_mask_area_threshold (
float,可选,默认值为 0.8) — 用于将掩码合并为单个分割区域的面积重叠阈值。 - label_ids_to_fuse (
set[int],可选) — 应在不连续区域之间进行融合的标签 ID。
返回值
list[dict]
一个字典列表(每帧一个),每个字典包含:
"segmentation"— 一个形状为(height, width)的torch.Tensor,包含分割 ID(背景为 -1)。"segments_info"— 一个字典列表,每个字典包含每个片段的"id"、"label_id"和"score"。
将 VideomtForUniversalSegmentation 的输出转换为全景分割预测。
VideomtConfig
class transformers.VideomtConfig
< 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 = Nonehidden_size: int = 1024num_hidden_layers: int = 24num_attention_heads: int = 16hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 640patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3mlp_ratio: int = 4layerscale_value: float = 1.0drop_path_rate: float | int = 0.0num_upscale_blocks: int = 2attention_dropout: float | int = 0.0use_swiglu_ffn: bool = Falsenum_blocks: int = 4no_object_weight: float = 0.1class_weight: float = 2.0mask_weight: float = 5.0dice_weight: float = 5.0train_num_points: int = 12544oversample_ratio: float = 3.0importance_sample_ratio: float = 0.75num_queries: int = 200num_register_tokens: int = 4 )
参数
- hidden_size (
int,可选,默认为1024) — 隐藏表示的维度。 - num_hidden_layers (
int,可选,默认为24) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为16) — Transformer 解码器中每个注意力层的注意力头数量。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - hidden_dropout_prob (
Union[float, int],可选,默认为0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为640) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - mlp_ratio (
int,可选,默认为4) — MLP 隐藏层维度与嵌入维度的比值。 - layerscale_value (
float,可选,默认为 1.0) — LayerScale 参数的初始值。 - drop_path_rate (
Union[float, int],可选,默认为0.0) — 用于 patch fusion 的 drop path 比率。 - num_upscale_blocks (
int,可选,默认为 2) — 解码器或分割头中使用的上采样块数量。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - use_swiglu_ffn (
bool,可选,默认为False) — 是否使用 SwiGLU 前馈神经网络。 - num_blocks (
int,可选,默认为 4) — 架构中特征块或阶段的数量。 - no_object_weight (
float,可选,默认值为 0.1) — 全景/实例分割中“无对象”类别的损失权重。 - class_weight(
float,可选,默认值为 2.0)— 分类目标的损失权重。 - mask_weight (
float,可选,默认为 5.0) — 掩码预测的损失权重。 - dice_weight (
float,可选,默认为5.0) — 全景分割损失中 dice 损失的相对权重。 - train_num_points (
int,可选,默认为 12544) — 训练期间用于计算掩码损失的采样点数。 - oversample_ratio (
float,可选,默认值为 3.0) — 用于掩码训练点采样的过采样率。 - importance_sample_ratio (
float,可选,默认值为 0.75) — 训练期间基于重要性采样的点比例。 - num_queries (
int,可选,默认为 200) — Transformer 中对象查询的数量。 - num_register_tokens (
int,可选,默认为 4) — 添加到 Transformer 输入中的可学习寄存器 token 数量。
这是用于存储 VideomtModel 配置的类。它根据指定的参数实例化 Videomt 模型,并定义模型架构。使用默认值实例化配置,将得到与 tue-mps/videomt-dinov2-small-ytvis2019
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
VideomtPreTrainedModel
class transformers.VideomtPreTrainedModel
< source >( config: PreTrainedConfig*inputs**kwargs )
参数
- config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
VideomtForUniversalSegmentation
class transformers.VideomtForUniversalSegmentation
< source >( config: VideomtConfig )
参数
- config (VideomtConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有顶部 head 的 Videomt 模型,用于实例/语义/全景分割。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values_videos: typing.Optional[torch.Tensor] = Nonemask_labels: list[torch.Tensor] | None = Noneclass_labels: list[torch.Tensor] | None = Nonepatch_offsets: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → VideomtForUniversalSegmentationOutput or tuple(torch.Tensor)
参数
- pixel_values_videos (
torch.Tensor,可选) — 形状为(batch_size, num_frames, num_channels, height, width)的视频输入。 - mask_labels (
list[torch.Tensor],可选) — 不支持 5D 视频输入。 - class_labels (
list[torch.LongTensor],可选) — 不支持 5D 视频输入。 - patch_offsets (
list[torch.Tensor],可选) — 对于视频输入未使用,仅保留以兼容模块化设计。
返回值
VideomtForUniversalSegmentationOutput 或 tuple(torch.Tensor)
VideomtForUniversalSegmentationOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(VideomtConfig)和输入。
VideomtForUniversalSegmentation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.Tensor, 可选) — 计算得到的损失,在存在标签时返回。 - class_queries_logits (
torch.Tensor, 可选) — 形状为(batch_size, num_queries, num_labels + 1)的张量,表示每个查询所提议的类别。请注意,+ 1是必需的,因为我们纳入了空类别。 - masks_queries_logits (
torch.Tensor, 可选) — 形状为(batch_size, num_queries, height, width)的张量,表示每个查询对应的预测掩码。 - last_hidden_state(形状为
(batch_size, num_channels, height, width)的torch.Tensor)— 最后一层的最后隐藏状态(最终特征图)。 - hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每个阶段的输出),形状为(batch_size, sequence_length, hidden_size)。模型所有层的隐藏状态。 - attentions (
tuple(tuple(torch.Tensor)),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个tuple(torch.Tensor)元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。