# 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](https://huggingface.co/papers/2602.17807) 中提出。Video Encoder-only Mask Transformer (VidEoMT) 是一个用于在线视频分割的轻量级纯编码器模型，基于普通的 [Vision Transformer (ViT)](vit) 构建。它是 [EoMT](./eomt) 在视频领域的最小化扩展，在 ViT 编码器内部同时执行空间和时间推理，无需依赖专门的跟踪模块或繁重的任务特定头部。

该论文的摘要如下：

*现有的在线视频分割模型通常将逐帧分割器与复杂的专用跟踪模块相结合。尽管有效，但这些模块引入了显著的架构复杂性和计算开销。近期的研究表明，当具备足够的容量并进行大规模预训练时，普通的视觉 Transformer（ViT）编码器无需专用模块即可执行准确的图像分割。受此观察启发，我们提出了仅编码器的视频掩码 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 支持三种视频分割任务：**实例**、**语义**和**全景**分割，每种任务在视频处理器上都有专用的后处理方法。

该模型由 [nielsr](https://huggingface.co/nielsr) 贡献。原始代码可在[此处](https://github.com/tue-mps/videomt)找到。

## 架构信息

VidEoMT 基于 [EoMT](./eomt) 构建，后者将带有 **register tokens** 的普通 DINOv2 预训练 Vision Transformer 重新用作分割模型。EoMT 在 ViT 编码器内部直接引入了可学习的 **object queries** 和一个轻量级的 **mask prediction head**，从而无需使用任务特定的解码器。

VidEoMT 通过以下两个关键扩展将其应用于视频：

1. **查询传播**：来自上一帧的对象查询通过线性投影（`query_updater`）传递到下一帧，从而无需专用跟踪器即可实现时序推理。
2. **查询融合**：将传播的查询与一组与时间无关的学习查询相加，使模型能够适应视频中出现的新的对象。

早期的编码器层独立（并行）处理所有帧，而最后的块则针对每一帧使用融合后的查询进行操作，从而生成逐帧的掩码和类别预测。

## 使用示例

使用 Hugging Face 的 VidEoMT 实现，配合预训练模型进行推理。以下示例复用公开的 `tue-mps/videomt-dinov2-small-ytvis2019` 检查点，以演示在示例视频上执行视频实例、语义和全景后处理。

### 视频实例分割

```python
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()
```

### 视频语义分割

```python
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()
```

### 视频全景分割

```python
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[[transformers.VideomtVideoProcessor]]

#### transformers.VideomtVideoProcessor[[transformers.VideomtVideoProcessor]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/video_processing_videomt.py#L147)

**参数：**

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 为整数时，是否在调整大小时默认使用正方形图像。

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'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([VideosKwargs](/docs/transformers/main/zh/main_classes/processors#transformers.VideosKwargs), *optional*) : 每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

构建一个 VideomtVideoProcessor 视频处理器。

#### post_process_semantic_segmentation[[transformers.VideomtVideoProcessor.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list, return_segmentation_scores: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/video_processing_videomt.py#L178)

**参数：**

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](/docs/transformers/main/zh/model_doc/videomt#transformers.VideomtForUniversalSegmentation) 的输出转换为语义分割预测。

#### post_process_instance_segmentation[[transformers.VideomtVideoProcessor.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, target_sizes: list, threshold: float = 0.5)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/video_processing_videomt.py#L232)

**参数：**

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](/docs/transformers/main/zh/model_doc/videomt#transformers.VideomtForUniversalSegmentation) 的输出转换为实例分割预测。

#### post_process_panoptic_segmentation[[transformers.VideomtVideoProcessor.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, target_sizes: list, threshold: float = 0.8, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/video_processing_videomt.py#L301)

**参数：**

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](/docs/transformers/main/zh/model_doc/videomt#transformers.VideomtForUniversalSegmentation) 的输出转换为全景分割预测。

## VideomtConfig[[transformers.VideomtConfig]]

#### transformers.VideomtConfig[[transformers.VideomtConfig]]

```python
transformers.VideomtConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 1024, num_hidden_layers: int = 24, num_attention_heads: int = 16, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, int] = 640, patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, mlp_ratio: int = 4, layerscale_value: float = 1.0, drop_path_rate: float | int = 0.0, num_upscale_blocks: int = 2, attention_dropout: float | int = 0.0, use_swiglu_ffn: bool = False, 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, train_num_points: int = 12544, oversample_ratio: float = 3.0, importance_sample_ratio: float = 0.75, num_queries: int = 200, num_register_tokens: int = 4)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/configuration_videomt.py#L29)

**参数：**

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 融合的 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](https://huggingface.co/tue-mps/videomt-dinov2-small-ytvis2019)

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import VideomtConfig, VideomtForUniversalSegmentation

>>> # Initialize configuration
>>> config = VideomtConfig()

>>> # Initialize model
>>> model = VideomtForUniversalSegmentation(config)

>>> # Access config
>>> config = model.config
```

## VideomtPreTrainedModel[[transformers.VideomtPreTrainedModel]]

#### transformers.VideomtPreTrainedModel[[transformers.VideomtPreTrainedModel]]

```python
transformers.VideomtPreTrainedModel(config: PreTrainedConfig, *inputs, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/modeling_videomt.py#L924)

**参数：**

config ([PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.VideomtPreTrainedModel.forward]]

```python
forward(*args, **kwargs)
```

点分路径（例如 `torch.float32`）的模拟值：属性访问链和调用行为如同透传装饰器，`repr` 为点分路径，将其用作基类时会替换为普通的 `type` 基类（PEP 560 `__mro_entries__`），因此真实的子类保留正常的元类，且 `inspect.signature` 读取的是它们真实的 `__init__`，而非模拟对象的。

## VideomtForUniversalSegmentation[[transformers.VideomtForUniversalSegmentation]]

#### transformers.VideomtForUniversalSegmentation[[transformers.VideomtForUniversalSegmentation]]

```python
transformers.VideomtForUniversalSegmentation(config: VideomtConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/modeling_videomt.py#L1044)

**参数：**

config ([VideomtConfig](/docs/transformers/main/zh/model_doc/videomt#transformers.VideomtConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

带有顶部 head 的 Videomt 模型，用于实例/语义/全景分割。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.VideomtForUniversalSegmentation.forward]]

```python
forward(pixel_values_videos: typing.Optional[torch.Tensor] = None, mask_labels: list[torch.Tensor] | None = None, class_labels: list[torch.Tensor] | None = None, patch_offsets: list[torch.Tensor] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/videomt/modeling_videomt.py#L1103)

**参数：**

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](/docs/transformers/main/zh/model_doc/videomt#transformers.VideomtConfig)）和输入。

[VideomtForUniversalSegmentation](/docs/transformers/main/zh/model_doc/videomt#transformers.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 解码器的自注意力和交叉注意力权重。

