Transformers 文档

Mask2Former

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Mask2Former

PyTorch

概述

Mask2Former 模型由 Bowen Cheng、Ishan Misra、Alexander G. Schwing、Alexander Kirillov 和 Rohit Girdhar 在 用于通用图像分割的 Masked-attention Mask Transformer 中提出。 Mask2Former 是一个用于全景、实例和语义分割的统一框架,与 MaskFormer 相比,在性能和效率方面都有显著提升。

论文摘要如下:

图像分割将具有不同语义的像素分组,例如,类别或实例成员关系。每种语义选择都定义了一个任务。虽然每个任务的语义各不相同,但当前的研究重点是为每个任务设计专门的架构。我们提出了 Masked-attention Mask Transformer (Mask2Former),这是一种能够处理任何图像分割任务(全景、实例或语义)的新架构。其关键组件包括掩码注意力,它通过约束预测掩码区域内的交叉注意力来提取局部特征。除了将研究工作量减少至少三倍外,它在四个流行的数据集上显著优于最佳专用架构。最值得注意的是,Mask2Former 为全景分割(COCO 上 57.8 PQ)、实例分割(COCO 上 50.1 AP)和语义分割(ADE20K 上 57.7 mIoU)设定了新的最先进水平。

图纸 Mask2Former 架构。 摘自原始论文。

此模型由 Shivalika SinghAlara Dirik 贡献。 原始代码可以在此处找到。

使用技巧

资源

官方 Hugging Face 和社区(🌎 表示)资源列表,可帮助您开始使用 Mask2Former。

  • 关于推理 + 在自定义数据上微调 Mask2Former 的演示 notebook 可以在此处找到。
  • 使用 TrainerAccelerate 微调 Mask2Former 的脚本可以在此处找到。

如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核。 该资源最好展示一些新的东西,而不是复制现有资源。

Mask2FormerConfig

class transformers.Mask2FormerConfig

< >

( backbone_config: typing.Optional[typing.Dict] = None feature_size: int = 256 mask_feature_size: int = 256 hidden_dim: int = 256 encoder_feedforward_dim: int = 1024 activation_function: str = 'relu' encoder_layers: int = 6 decoder_layers: int = 10 num_attention_heads: int = 8 dropout: float = 0.0 dim_feedforward: int = 2048 pre_norm: bool = False enforce_input_projection: bool = False common_stride: int = 4 ignore_value: int = 255 num_queries: int = 100 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 init_std: float = 0.02 init_xavier_std: float = 1.0 use_auxiliary_loss: bool = True feature_strides: typing.List[int] = [4, 8, 16, 32] output_auxiliary_logits: bool = None backbone: typing.Optional[str] = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: typing.Optional[typing.Dict] = None **kwargs )

参数

  • backbone_config (PretrainedConfigdict, 可选,默认为 SwinConfig()) — backbone 模型的配置。 如果未设置,将使用与 swin-base-patch4-window12-384 对应的配置。
  • backbone (str, 可选) — 当 backbone_configNone 时,要使用的 backbone 名称。 如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。 如果 use_pretrained_backboneFalse,这将加载 backbone 的配置并使用它来初始化具有随机权重的 backbone。
  • use_pretrained_backbone (bool, 可选, False) — 是否为 backbone 使用预训练权重。
  • use_timm_backbone (bool, 可选, False) — 是否从 timm 库加载 backbone。 如果 False,则从 transformers 库加载 backbone。
  • backbone_kwargs (dict, 可选) — 从检查点加载时要传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。 如果设置了 backbone_config,则无法指定。
  • feature_size (int, 可选,默认为 256) — 结果特征图的特征(通道)数量。
  • mask_feature_size (int, 可选,默认为 256) — mask 的特征大小,此值也将用于指定特征金字塔网络(Feature Pyramid Network)的特征大小。
  • hidden_dim (int, 可选,默认为 256) — 编码器层的维度。
  • encoder_feedforward_dim (int, 可选,默认为 1024) — 用作像素解码器一部分的可变形 DETR 编码器的前馈网络维度。
  • encoder_layers (int, 可选,默认为 6) — 用作像素解码器一部分的可变形 DETR 编码器中的层数。
  • decoder_layers (int, 可选,默认为 10) — Transformer 解码器中的层数。
  • num_attention_heads (int, 可选,默认为 8) — 每个注意力层的注意力头数。
  • dropout (float, 可选,默认为 0.1) — 嵌入层、编码器中所有全连接层的 dropout 概率。
  • dim_feedforward (int, 可选,默认为 2048) — Transformer 解码器中前馈网络的特征维度。
  • pre_norm (bool, 可选,默认为 False) — 是否对 Transformer 解码器使用预 LayerNorm。
  • enforce_input_projection (bool, 可选,默认为 False) — 即使 Transformer 解码器中的输入通道和隐藏维度相同,是否添加输入投影 1x1 卷积。
  • common_stride (int, 可选,默认为 4) — 用于确定用作像素解码器一部分的 FPN 层数的参数。
  • ignore_value (int, 可选,默认为 255) — 训练期间要忽略的类别 ID。
  • num_queries (int, 可选,默认为 100) — 解码器的查询数量。
  • no_object_weight (int, 可选,默认为 0.1) — 应用于 null(无对象)类别的权重。
  • class_weight (int, 可选,默认为 2.0) — 交叉熵损失的权重。
  • mask_weight (int, 可选,默认为 5.0) — mask 损失的权重。
  • dice_weight (int, 可选,默认为 5.0) — dice 损失的权重。
  • train_num_points (strfunction, 可选,默认为 12544) — 损失计算期间用于采样的点数。
  • oversample_ratio (float, 可选,默认为 3.0) — 用于计算采样点数的过采样参数。
  • importance_sample_ratio (float, 可选,默认为 0.75) — 通过重要性采样采样的点的比例。
  • init_std (float, 可选,默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • init_xavier_std (float, 可选,默认为 1.0) — 用于 HM 注意力映射模块中 Xavier 初始化增益的缩放因子。
  • use_auxiliary_loss (boolean, 可选, 默认为 True) — 如果为 True,则 Mask2FormerForUniversalSegmentationOutput 将包含使用来自每个解码器阶段的 logits 计算的辅助损失。
  • feature_strides (List[int], 可选,默认为 [4, 8, 16, 32]) — 从骨干网络生成的特征对应的特征步幅。
  • output_auxiliary_logits (bool, 可选) — 模型是否应输出其 auxiliary_logits

这是用于存储 Mask2FormerModel 配置的配置类。它用于根据指定的参数实例化 Mask2Former 模型,定义模型架构。使用默认值实例化配置将产生与 Mask2Former facebook/mask2former-swin-small-coco-instance 架构类似的配置。

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

目前,Mask2Former 仅支持 Swin Transformer 作为骨干网络。

示例

>>> from transformers import Mask2FormerConfig, Mask2FormerModel

>>> # Initializing a Mask2Former facebook/mask2former-swin-small-coco-instance configuration
>>> configuration = Mask2FormerConfig()

>>> # Initializing a model (with random weights) from the facebook/mask2former-swin-small-coco-instance style configuration
>>> model = Mask2FormerModel(configuration)

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

from_backbone_config

< >

( backbone_config: PretrainedConfig **kwargs ) Mask2FormerConfig

参数

返回:

Mask2FormerConfig

配置对象的实例

从预训练的主干模型配置实例化一个 Mask2FormerConfig (或派生类)。

MaskFormer 特定输出

class transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutput

< >

( encoder_last_hidden_state: FloatTensor = None pixel_decoder_last_hidden_state: FloatTensor = None transformer_decoder_last_hidden_state: FloatTensor = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None transformer_decoder_intermediate_states: typing.Tuple[torch.FloatTensor] = None masks_queries_logits: typing.Tuple[torch.FloatTensor] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

参数

  • encoder_last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)可选) — 编码器模型(主干网络)最后一级的最后隐藏状态(最终特征图)。当传递 output_hidden_states=True 时返回。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可选) — torch.FloatTensor 的元组(每个嵌入输出 + 每个阶段的输出各一个),形状为 (batch_size, num_channels, height, width)。编码器模型在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • pixel_decoder_last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)可选) — 像素解码器模型最后一级的最后隐藏状态(最终特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个嵌入输出 + 每个阶段的输出各一个),形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — Transformer 解码器的最终输出,形状为 (batch_size, sequence_length, hidden_size)
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选) — torch.FloatTensor 的元组(每个嵌入输出 + 每个阶段的输出各一个),形状为 (batch_size, sequence_length, hidden_size)。Transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • transformer_decoder_intermediate_states (形状为 (num_queries, 1, hidden_size)tuple(torch.FloatTensor)) — 中间解码器激活值,即每个解码器层的输出,每个输出都经过了层归一化 (layernorm)。
  • masks_queries_logits (形状为 (batch_size, num_queries, height, width)tuple(torch.FloatTensor)) — 来自 Transformer 解码器中每一层的 Mask 预测。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选,当传递 output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组(每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 Transformer 解码器的自注意力权重。

用于 Mask2FormerModel 输出的类。此类返回计算 logits 所需的所有隐藏状态。

class transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None class_queries_logits: FloatTensor = None masks_queries_logits: FloatTensor = None auxiliary_logits: typing.Optional[typing.List[typing.Dict[str, torch.FloatTensor]]] = None encoder_last_hidden_state: FloatTensor = None pixel_decoder_last_hidden_state: FloatTensor = None transformer_decoder_last_hidden_state: FloatTensor = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

参数

  • loss (torch.Tensor, 可选) — 计算出的损失值,当存在标签时返回。
  • class_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, num_labels + 1) 的张量,表示每个查询的提议类别。请注意,由于我们合并了空类别,因此需要 + 1
  • masks_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, height, width) 的张量,表示每个查询的提议掩码。
  • auxiliary_logits (List[Dict(str, torch.FloatTensor)], 可选) — 来自 Transformer 解码器每一层的类别和掩码预测列表。
  • encoder_last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)) — 编码器模型(主干网络)最后一级的最后隐藏状态(最终特征图)。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个嵌入输出 + 每个阶段的输出各一个),形状为 (batch_size, num_channels, height, width)。编码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • pixel_decoder_last_hidden_state (torch.FloatTensor, 形状为 (batch_size, num_channels, height, width)) — 像素解码器模型最后一级的最后隐藏状态(最终特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(每个嵌入输出 + 每个阶段的输出各一个),形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — transformer 解码器的最终输出 (batch_size, sequence_length, hidden_size)
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (每个阶段的输出一个,加上嵌入层的输出一个),形状为 (batch_size, sequence_length, hidden_size)。transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组 (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力权重和交叉注意力权重。

用于 Mask2FormerForUniversalSegmentationOutput 输出的类。

此输出可以直接传递给 post_process_semantic_segmentation()post_process_instance_segmentation()post_process_panoptic_segmentation() 以计算最终的分割图。请参阅 [`~Mask2FormerImageProcessor] 以获取有关用法的详细信息。

Mask2FormerModel

class transformers.Mask2FormerModel

< >

( config: Mask2FormerConfig )

参数

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

裸 Mask2Former 模型,输出原始隐藏状态,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: Tensor pixel_mask: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 AutoImageProcessor.preprocess
  • pixel_mask (形状为 (batch_size, height, width)torch.LongTensor, 可选) — 用于避免对 padding 像素值执行注意力的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示真实像素(即未被掩码),
    • 0 表示 padding 像素(即被掩码)。

    什么是注意力掩码?

  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • output_attentions (bool, 可选) — 是否返回 Detr 解码器注意力层的注意力张量。
  • return_dict (bool, 可选) — 是否返回 ~Mask2FormerModelOutput 而不是普通元组。

返回:

transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutputtuple(torch.FloatTensor)

一个 transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutputtorch.FloatTensor 的元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (Mask2FormerConfig) 和输入。

  • encoder_last_hidden_state (形状为 (batch_size, num_channels, height, width)torch.FloatTensor, 可选) — 编码器模型(backbone)最后一层的最后隐藏状态(最终特征图)。当传递 output_hidden_states=True 时返回。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可选) — torch.FloatTensor 的元组 (每个阶段的输出一个,加上嵌入层的输出一个),形状为 (batch_size, num_channels, height, width)。编码器模型在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • pixel_decoder_last_hidden_state (形状为 (batch_size, num_channels, height, width)torch.FloatTensor, 可选) — 像素解码器模型最后一层的最后隐藏状态(最终特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), , 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (每个阶段的输出一个,加上嵌入层的输出一个),形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — transformer 解码器的最终输出 (batch_size, sequence_length, hidden_size)
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选) — torch.FloatTensor 的元组 (每个阶段的输出一个,加上嵌入层的输出一个),形状为 (batch_size, sequence_length, hidden_size)。transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。当传递 output_hidden_states=True 时返回。
  • transformer_decoder_intermediate_states (形状为 (num_queries, 1, hidden_size)tuple(torch.FloatTensor)) — 中间解码器激活,即每个解码器层的输出,每个输出都经过了 layernorm。
  • masks_queries_logits (形状为 (batch_size, num_queries, height, width)tuple(torch.FloatTensor)) 来自 transformer 解码器中每层的掩码预测。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组 (每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自 transformer 解码器的自注意力权重。

Mask2FormerModelOutput

Mask2FormerModel 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数内定义,但应该在之后调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> import torch
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoImageProcessor, Mask2FormerModel

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

>>> # load image preprocessor and Mask2FormerModel trained on COCO instance segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-coco-instance")
>>> model = Mask2FormerModel.from_pretrained("facebook/mask2former-swin-small-coco-instance")
>>> inputs = image_processor(image, return_tensors="pt")

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # model outputs last hidden states of shape (batch_size, num_queries, hidden_size)
>>> print(outputs.transformer_decoder_last_hidden_state.shape)
torch.Size([1, 100, 256])

Mask2FormerForUniversalSegmentation

class transformers.Mask2FormerForUniversalSegmentation

< >

( config: Mask2FormerConfig )

参数

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

带有用于实例/语义/全景分割的 head 的 Mask2Former 模型。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: Tensor mask_labels: typing.Optional[typing.List[torch.Tensor]] = None class_labels: typing.Optional[typing.List[torch.Tensor]] = None pixel_mask: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_auxiliary_logits: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 AutoImageProcessor.preprocess
  • pixel_mask (形状为 (batch_size, height, width)torch.LongTensor, 可选) — 用于避免对 padding 像素值执行注意力的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示真实像素(即未被掩码),
    • 0 表示 padding 像素(即被掩码)。

    什么是注意力掩码?

  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • output_attentions (bool, 可选) — 是否返回 Detr 解码器注意力层的注意力张量。
  • return_dict (bool, 可选) — 是否返回 ~Mask2FormerModelOutput 而不是普通元组。
  • 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] 的标签。

返回:

transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutputtuple(torch.FloatTensor)

一个 transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput 或一个 torch.FloatTensor 元组 (如果传递了 return_dict=False 或者当 config.return_dict=False 时),包含各种元素,具体取决于配置 (Mask2FormerConfig) 和输入。

  • loss (torch.Tensor, 可选) — 计算出的损失值,当存在标签时返回。
  • class_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, num_labels + 1) 的张量,表示每个查询的提议类别。 请注意,需要 + 1 是因为我们加入了 null 类。
  • masks_queries_logits (torch.FloatTensor) — 形状为 (batch_size, num_queries, height, width) 的张量,表示每个查询的提议掩码。
  • auxiliary_logits (List[Dict(str, torch.FloatTensor)], 可选) — 来自 transformer 解码器每一层的类别和掩码预测列表。
  • encoder_last_hidden_state (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 编码器模型(骨干网络)最后一级的最后隐藏状态(最终特征图)。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组 (embeddings 的输出一个,加上每一级输出一个),形状为 (batch_size, num_channels, height, width)。 编码器模型在每一级输出的隐藏状态(也称为特征图)。
  • pixel_decoder_last_hidden_state (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素解码器模型最后一级的最后隐藏状态(最终特征图)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组 (embeddings 的输出一个,加上每一级输出一个),形状为 (batch_size, num_channels, height, width)。 像素解码器模型在每一级输出的隐藏状态(也称为特征图)。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — transformer 解码器的最终输出 (batch_size, sequence_length, hidden_size)
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组 (embeddings 的输出一个,加上每一级输出一个),形状为 (batch_size, sequence_length, hidden_size)。 transformer 解码器在每一级输出的隐藏状态(也称为特征图)。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — tuple(torch.FloatTensor) 元组 (每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。 来自 transformer 解码器的自注意力权重和交叉注意力权重。

Mask2FormerUniversalSegmentationOutput

Mask2FormerForUniversalSegmentation 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数内定义,但应该在之后调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

实例分割示例

>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch

>>> # Load Mask2Former trained on COCO instance segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-coco-instance")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
...     "facebook/mask2former-swin-small-coco-instance"
... )

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # Perform post-processing to get instance segmentation map
>>> pred_instance_map = image_processor.post_process_instance_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_instance_map.shape)
torch.Size([480, 640])

语义分割示例

>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch

>>> # Load Mask2Former trained on ADE20k semantic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-ade-semantic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained("facebook/mask2former-swin-small-ade-semantic")

>>> url = (
...     "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
... )
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # Perform post-processing to get semantic segmentation map
>>> pred_semantic_map = image_processor.post_process_semantic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_semantic_map.shape)
torch.Size([512, 683])

全景分割示例

>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch

>>> # Load Mask2Former trained on CityScapes panoptic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-cityscapes-panoptic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
...     "facebook/mask2former-swin-small-cityscapes-panoptic"
... )

>>> url = "https://cdn-media.huggingface.co/Inference-API/Sample-results-on-the-Cityscapes-dataset-The-above-images-show-how-our-method-can-handle.png"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # Perform post-processing to get panoptic segmentation map
>>> pred_panoptic_map = image_processor.post_process_panoptic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> print(pred_panoptic_map.shape)
torch.Size([338, 676])

Mask2FormerImageProcessor

class transformers.Mask2FormerImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None size_divisor: int = 32 resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float]] = None image_std: typing.Union[float, typing.List[float]] = None ignore_index: typing.Optional[int] = None do_reduce_labels: bool = False num_labels: typing.Optional[int] = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将输入调整为特定的 size
  • size (int, 可选, 默认为 800) — 将输入调整为给定大小。 仅当 do_resize 设置为 True 时才有效。 如果 size 是类似 (width, height) 的序列,则输出大小将与之匹配。 如果 size 是一个整数,则图像的较小边缘将与此数字匹配。 即,如果 height > width,则图像将被缩放到 (size * height / width, size)
  • size_divisor (int, 可选, 默认为 32) — 一些骨干网络需要图像可以被某个数字整除。 如果未传递,则默认为 Swin Transformer 中使用的值。
  • resample (int, 可选, 默认为 Resampling.BILINEAR) — 可选的重采样过滤器。 这可以是 PIL.Image.Resampling.NEAREST, PIL.Image.Resampling.BOX, PIL.Image.Resampling.BILINEAR, PIL.Image.Resampling.HAMMING, PIL.Image.Resampling.BICUBICPIL.Image.Resampling.LANCZOS 之一。 仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool, 可选, 默认为 True) — 是否将输入重新缩放到某个 scale
  • rescale_factor (float, 可选, 默认为 1/ 255) — 按给定因子重新缩放输入。 仅当 do_rescale 设置为 True 时才有效。
  • do_normalize (bool, 可选, 默认为 True) — 是否使用均值和标准差来标准化输入。
  • image_mean (int, 可选, 默认为 [0.485, 0.456, 0.406]) — 每个通道的均值序列,用于标准化图像时使用。 默认为 ImageNet 均值。
  • image_std (int, 可选, 默认为 [0.229, 0.224, 0.225]) — 每个通道的标准差序列,用于标准化图像时使用。 默认为 ImageNet 标准差。
  • ignore_index (int, 可选) — 要分配给分割图中背景像素的标签。 如果提供,则分割图上标记为 0(背景)的像素将被替换为 ignore_index
  • do_reduce_labels (bool, 可选, 默认为 False) — 是否将分割图的所有标签值减 1。 通常用于数据集,其中 0 用于背景,而背景本身不包含在数据集的所有类别中(例如 ADE20k)。 背景标签将被 ignore_index 替换。
  • num_labels (int, 可选) — 分割图中的标签数量。

构建 Mask2Former 图像处理器。 图像处理器可用于为模型准备图像和可选目标。

此图像处理器继承自 BaseImageProcessor,其中包含大多数主要方法。 用户应参考此超类以获取有关这些方法的更多信息。

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: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None instance_id_to_semantic_id: typing.Optional[typing.Dict[int, int]] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None size_divisor: typing.Optional[int] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None ignore_index: typing.Optional[int] = None do_reduce_labels: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

encode_inputs

< >

( pixel_values_list: typing.List[typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]] segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] = None instance_id_to_semantic_id: typing.Union[typing.List[typing.Dict[int, int]], typing.Dict[int, int], NoneType] = None ignore_index: typing.Optional[int] = None do_reduce_labels: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) BatchFeature

参数

  • pixel_values_list (List[ImageInput]) — 要填充的图像(像素值)列表。 每个图像应为形状为 (channels, height, width) 的张量。
  • segmentation_maps (ImageInput, 可选) — 相应的语义分割图,带有像素级注释。

    bool可选,默认为 True):是否将图像填充到批次中最大的图像,并创建像素掩码。

    如果保留为默认值,将返回一个像素掩码,该掩码为:

    • 对于真实像素(即未掩码)为 1,
    • 对于填充像素(即已掩码)为 0。
  • instance_id_to_semantic_id (List[Dict[int, int]]Dict[int, int], 可选) — 对象实例 ID 和类别 ID 之间的映射。 如果传递,则 segmentation_maps 将被视为实例分割图,其中每个像素代表一个实例 ID。 可以作为具有全局/数据集级别映射的单个字典提供,也可以作为字典列表(每个图像一个)提供,以分别映射每个图像中的实例 ID。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回 tensor 而不是 NumPy 数组。 如果设置为 'pt',则返回 PyTorch torch.Tensor 对象。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未提供,则将进行推断。

返回:

BatchFeature

包含以下字段的 BatchFeature

  • pixel_values — 要馈送到模型的像素值。
  • pixel_mask — 要馈送到模型的像素掩码(当 =Truepixel_maskself.model_input_names 中时)。
  • mask_labels — 可选的掩码标签列表,形状为 (labels, height, width),用于馈送到模型(当提供 annotations 时)。
  • class_labels — 可选的类别标签列表,形状为 (labels),用于馈送到模型(当提供 annotations 时)。它们标识 mask_labels 的标签,例如,如果 class_labels[i][j],则为 mask_labels[i][j] 的标签。

将批次中的图像填充到最大图像尺寸,并创建相应的 pixel_mask

Mask2Former 使用掩码分类范式处理语义分割,因此输入分割图将转换为二进制掩码列表及其各自的标签。 让我们看一个例子,假设 segmentation_maps = [[2,6,7,9]],输出将包含 mask_labels = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]] (四个二进制掩码)和 class_labels = [2,6,7,9],每个掩码的标签。

post_process_semantic_segmentation

< >

( outputs target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None ) List[torch.Tensor]

参数

  • outputs (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
  • target_sizes (List[Tuple[int, int]], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于每个预测的请求最终大小(高度,宽度)。 如果留空,预测将不会调整大小。

返回:

List[torch.Tensor]

长度为 batch_size 的列表,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes)。 每个 torch.Tensor 的每个条目对应于一个语义类别 ID。

Mask2FormerForUniversalSegmentation 的输出转换为语义分割图。 仅支持 PyTorch。

post_process_instance_segmentation

< >

( outputs threshold: float = 0.5 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None return_coco_annotation: typing.Optional[bool] = False return_binary_maps: typing.Optional[bool] = False ) List[Dict]

参数

  • outputs (Mask2FormerForUniversalSegmentation) — 模型的原始输出。
  • threshold (float, 可选, 默认为 0.5) — 用于保留预测实例掩码的概率分数阈值。
  • mask_threshold (float, 可选, 默认为 0.5) — 将预测掩码转换为二进制值时使用的阈值。
  • overlap_mask_area_threshold (float, 可选, 默认为 0.8) — 重叠掩码区域阈值,用于合并或丢弃每个二进制实例掩码内的小型不连接部分。
  • target_sizes (List[Tuple], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于每个预测的请求最终大小(高度,宽度)。 如果留空,预测将不会调整大小。
  • return_coco_annotation (bool, 可选, 默认为 False) — 如果设置为 True,则分割图以 COCO 运行长度编码 (RLE) 格式返回。
  • return_binary_maps (bool, 可选, 默认为 False) — 如果设置为 True,则分割图将作为二进制分割图的串联张量返回(每个检测到的实例一个)。

返回:

List[Dict]

字典列表,每个图像一个字典,每个字典包含两个键

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id;或者,如果 return_coco_annotation 设置为 True,则为分割图的 List[List] 运行长度编码 (RLE);或者,如果 return_binary_maps 设置为 True,则为形状为 (num_instances, height, width) 的张量。 如果在 threshold 之上未找到掩码,则设置为 None
  • segments_info — 包含每个分割的其他信息的字典。
    • id — 表示 segment_id 的整数。
    • label_id — 表示与 segment_id 对应的标签/语义类别 ID 的整数。
    • scoresegment_id 的分割的预测分数。

Mask2FormerForUniversalSegmentationOutput 的输出转换为实例分割预测。 仅支持 PyTorch。 如果实例可能重叠,请将 return_coco_annotation 或 return_binary_maps 设置为 True 以获得正确的分割结果。

post_process_panoptic_segmentation

< >

( outputs threshold: float = 0.5 mask_threshold: float = 0.5 overlap_mask_area_threshold: float = 0.8 label_ids_to_fuse: typing.Optional[typing.Set[int]] = None target_sizes: typing.Optional[typing.List[typing.Tuple[int, int]]] = None ) List[Dict]

参数

  • outputs (Mask2FormerForUniversalSegmentationOutput) — 来自 Mask2FormerForUniversalSegmentation 的输出。
  • threshold (float, 可选, 默认为 0.5) — 用于保留预测实例掩码的概率分数阈值。
  • mask_threshold (float, 可选, 默认为 0.5) — 将预测掩码转换为二进制值时使用的阈值。
  • overlap_mask_area_threshold (float, 可选, 默认为 0.8) — 重叠掩码区域阈值,用于合并或丢弃每个二进制实例掩码内的小型不连接部分。
  • label_ids_to_fuse (Set[int], 可选) — 此状态下的标签将使其所有实例融合在一起。 例如,我们可以说一张图像中只能有一个天空,但可以有多个人,因此天空的标签 ID 将在该集合中,但人的标签 ID 不会。
  • target_sizes (List[Tuple], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于批次中每个预测的请求最终大小(高度,宽度)。 如果留空,预测将不会调整大小。

返回:

List[Dict]

字典列表,每个图像一个字典,每个字典包含两个键

  • segmentation — 形状为 (height, width) 的张量,其中每个像素代表一个 segment_id;如果在 threshold 之上未找到掩码,则设置为 None。 如果指定了 target_sizes,则分割将调整为相应的 target_sizes 条目。
  • segments_info — 包含每个分割的其他信息的字典。
    • id — 表示 segment_id 的整数。
    • label_id — 表示与 segment_id 对应的标签/语义类别 ID 的整数。
    • was_fused — 一个布尔值,如果 label_idlabel_ids_to_fuse 中则为 True,否则为 False。 同一类别/标签的多个实例被融合并分配了一个 segment_id
    • scoresegment_id 的分割的预测分数。

Mask2FormerForUniversalSegmentationOutput 的输出转换为图像全景分割预测。 仅支持 PyTorch。

< > Update on GitHub