Transformers 文档

EoMT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2025 年 3 月 24 日在 HF 论文中发表,并于 2025 年 6 月 27 日贡献给 Hugging Face Transformers。

EoMT

概述

仅编码器掩码 Transformer (Encoder-only Mask Transformer, EoMT) 模型是在 CVPR 2025 重点论文 Your ViT is Secretly an Image Segmentation Model 中提出的,作者为 Tommie Kerssies、Niccolò Cavagnero、Alexander Hermans、Narges Norouzi、Giuseppe Averta、Bastian Leibe、Gijs Dubbelman 和 Daan de Geus。EoMT 表明,视觉 Transformer (ViT) 无需任务特定的组件即可高效执行图像分割。

论文摘要如下:

视觉 Transformer (ViT) 在各种计算机视觉任务中表现出了卓越的性能和可扩展性。为了将单尺度 ViT 应用于图像分割,现有方法通常采用卷积适配器来生成多尺度特征,使用像素解码器融合这些特征,并利用 Transformer 解码器进行预测。在本文中,我们证明了这些任务特定组件引入的归纳偏置(inductive biases)可以由 ViT 本身学习,前提是拥有足够大的模型和广泛的预训练。基于这些发现,我们引入了仅编码器掩码 Transformer (EoMT),它重新利用纯 ViT 架构来进行图像分割。在大规模模型和预训练的支持下,EoMT 获得了与使用任务特定组件的最先进模型相似的分割精度。同时,由于其架构简单,EoMT 比这些方法快得多,例如在使用 ViT-L 时速度提升高达 4 倍。在各种模型规模下,EoMT 在分割精度和预测速度之间展示了最佳平衡,这表明与其增加架构复杂性,不如将计算资源投入到扩展 ViT 本身。

该模型由 Yaswanth Gali 贡献。原始代码可在 此处 找到。

架构信息

EoMT 模型使用带有寄存器标记 (register tokens) 的 DINOv2 预训练视觉 Transformer 作为其主干网络。EoMT 仅依赖于编码器来简化分割流程,消除了之前方法中常用的任务特定解码器的需求。

在架构上,EoMT 引入了一小组学习查询 (learned queries) 和一个轻量级的掩码预测模块。这些查询被注入到最终的编码器块中,从而实现图像块与对象查询之间的联合注意力 (joint attention)。在训练期间,应用掩码注意力 (masked attention) 来约束每个查询专注于其对应的区域——有效地模拟了交叉注意力。这种约束通过掩码退火策略 (mask annealing strategy) 逐渐消除,从而在不影响分割性能的情况下实现高效的无解码器推理

drawing

该模型支持语义分割、实例分割和全景分割,采用统一的架构和特定任务的后处理方法。

用法示例

使用 Hugging Face 实现的 EoMT 进行预训练模型推理。

语义分割

EoMT 模型使用滑动窗口推理执行语义分割。输入图像被调整大小,使短边匹配目标输入尺寸,然后将其分割为重叠的裁剪区域。每个裁剪区域依次通过模型。推理后,来自每个裁剪区域的预测逻辑(logits)被拼合在一起,并重新缩放到原始图像大小,从而获得最终的分割掩码。

注意
如果你想为语义分割使用自定义目标尺寸,请按以下格式指定:
{"shortest_edge": 512}
注意,此处未提供 longest_edge —— 这是有意为之。对于语义分割,图像通常缩放以使短边大于或等于目标尺寸,因此不需要 longest_edge。

import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation


model_id = "tue-mps/ade20k_semantic_eomt_large_512"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_semantic_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the segmentation mask
plt.imshow(preds[0])
plt.axis("off")
plt.title("Semantic Segmentation")
plt.show()

实例分割

EoMT 模型使用填充推理执行实例分割。输入图像被调整大小,使长边匹配目标输入尺寸,短边进行零填充以形成正方形。最终的掩码和类别逻辑通过后处理(改编自 Mask2Former)组合,生成统一的实例分割图,以及分段元数据,如分段 ID、类别标签和置信度分数。

注意
若要使用自定义目标尺寸,请将尺寸指定为以下格式的字典:
{"shortest_edge": 512, "longest_edge": 512}
对于实例和全景分割,输入图像都将缩放并填充到此目标尺寸。

import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation


model_id = "tue-mps/coco_instance_eomt_large_640"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_instance_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the segmentation mask
plt.imshow(preds[0]["segmentation"])
plt.axis("off")
plt.title("Instance Segmentation")
plt.show()

全景分割

EoMT 模型使用与实例分割相同的填充推理策略执行全景分割。在填充和归一化后,模型同时预测实体类(instances)和背景类(stuff,无定形区域)。最终的掩码和类别逻辑通过后处理(改编自 Mask2Former)组合,生成统一的全景分割图,以及分段元数据,如分段 ID、类别标签和置信度分数。

import matplotlib.pyplot as plt
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, EomtForUniversalSegmentation


model_id = "tue-mps/coco_panoptic_eomt_large_640"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id, device_map="auto")

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_panoptic_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the panoptic segmentation mask
plt.imshow(preds[0]["segmentation"])
plt.axis("off")
plt.title("Panoptic Segmentation")
plt.show()

EomtImageProcessor

class transformers.EomtImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.models.eomt.image_processing_eomt.EomtImageProcessorKwargs] )

参数

  • do_split_image (bool, kwargs, 可选, 默认为 self.do_split_image) — 是否将输入图像分割为重叠块以进行语义分割。如果设置为 True,输入图像将分割为大小为 size["shortest_edge"] 且带有重叠的块。否则,输入图像将被填充至目标尺寸。
  • ignore_index (int, kwargs, 可选, 默认为 self.ignore_index) — 分割图中背景像素所分配的标签。如果提供,标记为 0(背景)的分割图像素将被 ignore_index 替换。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 EomtImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] segmentation_maps: list[torch.Tensor] | None = None instance_id_to_semantic_id: dict[int, int] | None = None **kwargs: typing_extensions.Unpack[transformers.models.eomt.image_processing_eomt.EomtImageProcessorKwargs] ) ~image_processing_base.BatchFeature

参数

  • 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
  • segmentation_maps (ImageInput, 可选) — 要为相应图像预处理的分割图。
  • instance_id_to_semantic_id (list[dict[int, int]]dict[int, int], 可选) — 对象实例 ID 和类 ID 之间的映射。
  • do_split_image (bool, kwargs, 可选, 默认为 self.do_split_image) — 是否将输入图像分割为重叠块以进行语义分割。如果设置为 True,输入图像将分割为大小为 size["shortest_edge"] 且带有重叠的块。否则,输入图像将被填充至目标尺寸。
  • ignore_index (int, kwargs, 可选, 默认为 self.ignore_index) — 分割图中背景像素所分配的标签。如果提供,标记为 0(背景)的分割图像素将被 ignore_index 替换。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 列在上面;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_semantic_segmentation

< >

( outputs target_sizes: list size: dict[str, int] | None = None )

将模型输出后处理为最终的语义分割预测。

post_process_instance_segmentation

< >

( outputs target_sizes: list threshold: float = 0.8 size: dict[str, int] | None = None )

将模型输出后处理为实例分割预测。

post_process_panoptic_segmentation

< >

( outputs target_sizes: list threshold: float = 0.8 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 stuff_classes: list[int] | None = None size: dict[str, int] | None = None )

将模型输出后处理为最终的全景分割预测。

EomtImageProcessorPil

class transformers.EomtImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.eomt.image_processing_pil_eomt.EomtImageProcessorKwargs] )

参数

  • do_split_image (bool, kwargs, optional, 默认为 self.do_split_image) — 是否将输入图像分割成重叠的块以进行语义分割。如果设为 True,输入图像将被分割为大小为 size["shortest_edge"] 且块间有重叠的补丁(patches)。否则,输入图像将被填充(padded)至目标尺寸。
  • ignore_index (int, kwargs, optional, 默认为 self.ignore_index) — 分割图中指定给背景像素的标签。如果提供该参数,分割图中标记为 0(背景)的像素将被替换为 ignore_index
  • **kwargs (ImagesKwargs, optional) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 EomtImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] segmentation_maps: list[torch.Tensor] | None = None instance_id_to_semantic_id: dict[int, int] | None = None **kwargs: typing_extensions.Unpack[transformers.models.eomt.image_processing_pil_eomt.EomtImageProcessorKwargs] ) ~image_processing_base.BatchFeature

参数

  • 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
  • segmentation_maps (ImageInput, optional) — 待预处理的对应图像的分割图。
  • instance_id_to_semantic_id (list[dict[int, int]]dict[int, int], optional) — 对象实例 ID 与类 ID 之间的映射。
  • do_split_image (bool, kwargs, optional, 默认为 self.do_split_image) — 是否将输入图像分割成重叠的块以进行语义分割。如果设为 True,输入图像将被分割为大小为 size["shortest_edge"] 且块间有重叠的补丁。否则,输入图像将被填充至目标尺寸。
  • ignore_index (int, kwargs, optional, 默认为 self.ignore_index) — 分割图中指定给背景像素的标签。如果提供该参数,分割图中标记为 0(背景)的像素将被替换为 ignore_index
  • return_tensors (strTensorType, optional) — 如果设为 'pt',返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, optional) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_semantic_segmentation

< >

( outputs target_sizes: list size: dict[str, int] | None = None )

将模型输出后处理为最终的语义分割预测。

post_process_instance_segmentation

< >

( outputs target_sizes: list threshold: float = 0.8 size: dict[str, int] | None = None )

将模型输出后处理为实例分割预测。

post_process_panoptic_segmentation

< >

( outputs target_sizes: list threshold: float = 0.8 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 stuff_classes: list[int] | None = None size: dict[str, int] | None = None )

将模型输出后处理为最终的全景分割预测。

EomtConfig

class transformers.EomtConfig

< >

( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 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: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = 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 )

参数

  • hidden_size (int, optional, 默认为 1024) — 隐藏表示的维度。
  • num_hidden_layers (int, optional, 默认为 24) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int, optional, 默认为 16) — Transformer 解码器中每个注意力层的注意力头数。
  • hidden_act (str, optional, 默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu", "relu", "silu" 等。
  • hidden_dropout_prob (Union[float, int], optional, 默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的丢弃概率(dropout probability)。
  • initializer_range (float, optional, 默认值为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, 默认值为 1e-06) — 层归一化(layer normalization)层使用的 epsilon 值。
  • image_size (Union[int, list[int], tuple[int, int]], optional, 默认值为 640) — 每张图像的大小(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]], optional, 默认值为 16) — 每个分块(patch)的大小(分辨率)。
  • num_channels (int, optional, 默认值为 3) — 输入通道数。
  • mlp_ratio (int, optional, 默认值为 4) — MLP 隐藏维度与嵌入维度的比率。
  • layerscale_value (float, optional, 默认值为 1.0) — LayerScale 参数的初始值。
  • drop_path_rate (Union[float, int], optional, 默认值为 0.0) — 用于分块融合(patch fusion)的 drop path 比率。
  • num_upscale_blocks (int, optional, 默认值为 2) — 用于解码器或分割头中的上采样块数量。
  • attention_dropout (Union[float, int], optional, 默认值为 0.0) — 注意力概率的 dropout 比率。
  • use_swiglu_ffn (bool, optional, 默认值为 False) — 是否使用 SwiGLU 前馈神经网络。
  • num_blocks (int, optional, 默认值为 4) — 架构中特征块或阶段的数量。
  • no_object_weight (float, optional, 默认值为 0.1) — 全景/实例分割中“无目标(no object)”类的损失权重。
  • class_weight (float, optional, 默认值为 2.0) — 分类目标的损失权重。
  • mask_weight (float, optional, 默认值为 5.0) — 掩码预测的损失权重。
  • dice_weight (float, optional, 默认值为 5.0) — 全景分割损失中 Dice 损失的相对权重。
  • train_num_points (int, optional, 默认值为 12544) — 训练期间用于掩码损失计算的采样点数量。
  • oversample_ratio (float, optional, 默认值为 3.0) — 用于掩码训练中点采样的过采样比率。
  • importance_sample_ratio (float, optional, 默认值为 0.75) — 训练期间基于重要性采样的点比率。
  • num_queries (int, optional, 默认值为 200) — Transformer 中的目标查询数量。
  • num_register_tokens (int, optional, 默认值为 4) — 添加到 Transformer 输入中的可学习寄存器 token 数量。

这是用于存储 EomtModel 配置的配置类。它根据指定的参数实例化一个 Eomt 模型,并定义了模型的架构。使用默认值实例化配置将产生与 tue-mps/coco_panoptic_eomt_large_640 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import EomtConfig, EomtForUniversalSegmentation

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

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

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

EomtForUniversalSegmentation

class transformers.EomtForUniversalSegmentation

< >

( config: EomtConfig )

参数

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

用于实例/语义/全景分割的 EoMT 模型。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: Tensor mask_labels: list[torch.Tensor] | None = None class_labels: list[torch.Tensor] | None = None patch_offsets: list[torch.Tensor] | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) EomtForUniversalSegmentationOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor) — 对应于输入图像的张量。可以使用 EomtImageProcessor 获取像素值。详情请参阅 EomtImageProcessor.__call__()processor_class 使用 EomtImageProcessor 进行图像处理)。
  • mask_labels (list[torch.Tensor], 可选) — 形状为 (num_labels, height, width) 的掩码标签列表,将输入到模型中。
  • class_labels (list[torch.LongTensor], 可选) — 形状为 (num_labels, height, width) 的目标类别标签列表,将输入到模型中。它们用于标识 mask_labels 的类别,例如,如果 class_labels[i][j] 存在,则为 mask_labels[i][j] 的标签。
  • patch_offsets (list[torch.Tensor], 可选) — 元组列表,指示用于语义分割的图像索引以及图块(patch)的起始和结束位置。

返回

EomtForUniversalSegmentationOutputtuple(torch.FloatTensor)

EomtForUniversalSegmentationOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False 时),根据配置 (EomtConfig) 和输入包含各种元素。

EomtForUniversalSegmentation 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (torch.Tensor, 可选) — 计算出的损失,当存在标签时返回。
  • class_queries_logits (torch.FloatTensor可选,默认为 None) — 形状为 (batch_size, num_queries, num_labels + 1) 的张量,表示每个查询(query)的候选类别。注意,之所以需要 + 1,是因为我们合并了空类别(null class)。
  • masks_queries_logits (torch.FloatTensor, 可选, 默认为 None) — 形状为 (batch_size, num_queries, height, width) 的张量,表示每个查询的建议掩码。
  • last_hidden_state (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 最后一层的隐藏状态(最终特征图)。
  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(一个用于嵌入层的输出 + 每个阶段的输出)。模型每一层的隐藏状态。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — tuple(torch.FloatTensor) 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力和交叉注意力权重。
  • patch_offsets (list[torch.Tensor], 可选) — 元组列表,指示用于语义分割的图像索引以及图块(patch)的起始和结束位置。
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.