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 for Universal Image Segmentation中提出。Mask2Former 是一個用於全景、例項和語義分割的統一框架,與MaskFormer相比,其效能和效率都有顯著提升。

論文摘要如下:

影像分割將畫素按不同的語義(例如,類別或例項成員)進行分組。每種語義選擇定義一個任務。雖然只有每個任務的語義不同,但目前的研究重點是為每個任務設計專門的架構。我們提出了 Masked-attention Mask Transformer (Mask2Former),這是一種能夠處理任何影像分割任務(全景、例項或語義)的新架構。其關鍵元件包括掩碼注意力(masked attention),它透過將交叉注意力限制在預測的掩碼區域內來提取區域性特徵。除了將研究工作量至少減少三倍之外,它在四個流行資料集上顯著優於最佳專用架構。最值得注意的是,Mask2Former 在全景分割 (COCO 上 57.8 PQ)、例項分割 (COCO 上 50.1 AP) 和語義分割 (ADE20K 上 57.7 mIoU) 方面創造了新的最先進水平。

drawing Mask2Former 架構。摘自原始論文。

該模型由Shivalika SinghAlara Dirik 貢獻。原始程式碼可在此處找到。

使用技巧

資源

Hugging Face 官方和社群(🌎 表示)資源列表,幫助您開始使用 Mask2Former。

  • 關於 Mask2Former 在自定義資料上進行推理 + 微調的演示筆記本可以在此處找到。
  • 使用 TrainerAccelerate 微調 `Mask2Former` 的指令碼可以在此處找到。

如果您有興趣提交資源以供此處收錄,請隨時發起拉取請求,我們將對其進行審查。理想情況下,資源應展示新內容,而非重複現有資源。

Mask2FormerConfig

class transformers.Mask2FormerConfig

< >

( backbone_config: typing.Optional[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: list = [4, 8, 16, 32] output_auxiliary_logits: typing.Optional[bool] = None backbone: typing.Optional[str] = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: typing.Optional[dict] = None **kwargs )

引數

  • `backbone_config` (`PretrainedConfig` 或 `dict`, *可選*, 預設為 `SwinConfig()`) — 主幹模型的配置。如果未設定,將使用與 `swin-base-patch4-window12-384` 對應的配置。
  • `backbone` (`str`, *可選*) — 當 `backbone_config` 為 `None` 時使用的主幹名稱。如果 `use_pretrained_backbone` 為 `True`,這將從 timm 或 transformers 庫載入相應的預訓練權重。如果 `use_pretrained_backbone` 為 `False`,這將載入主幹的配置並使用它來初始化具有隨機權重的主幹。
  • `use_pretrained_backbone` (`bool`, *可選*, 預設為 `False`) — 是否使用主幹的預訓練權重。
  • `use_timm_backbone` (`bool`, *可選*, 預設為 `False`) — 是否從 timm 庫載入 `backbone`。如果為 `False`,則從 transformers 庫載入主幹。
  • `backbone_kwargs` (`dict`, *可選*) — 載入檢查點時傳遞給 AutoBackbone 的關鍵字引數,例如 `{'out_indices': (0, 1, 2, 3)}`。如果設定了 `backbone_config`,則不能指定此引數。
  • `feature_size` (`int`, *可選*, 預設為 256) — 生成特徵圖的特徵(通道)大小。
  • `mask_feature_size` (`int`, *可選*, 預設為 256) — 掩碼的特徵大小,此值也將用於指定特徵金字塔網路特徵的大小。
  • `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 解碼器是否使用 pre-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) — 應用於空(無物件)類別的權重。
  • `class_weight` (`int`, *可選*, 預設為 2.0) — 交叉熵損失的權重。
  • `mask_weight` (`int`, *可選*, 預設為 5.0) — 掩碼損失的權重。
  • `dice_weight` (`int`, *可選*, 預設為 5.0) — Dice 損失的權重。
  • `train_num_points` (`str` 或 `function`, *可選*, 預設為 12544) — 用於損失計算期間取樣的點數。
  • `oversample_ratio` (`float`, *可選*, 預設為 3.0) — 用於計算取樣點數的過取樣引數。
  • `importance_sample_ratio` (`float`, *可選*, 預設為 0.75) — 透過重要性取樣取樣的點數比例。
  • `init_std` (`float`, *可選*, 預設為 0.02) — 用於初始化所有權重矩陣的 `truncated_normal_initializer` 的標準差。
  • `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: typing.Optional[torch.FloatTensor] = None pixel_decoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None transformer_decoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[tuple[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[tuple[torch.FloatTensor]] = None transformer_decoder_intermediate_states: tuple = None masks_queries_logits: tuple = None attentions: typing.Optional[tuple[torch.FloatTensor]] = None )

引數

  • `encoder_last_hidden_state` (`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)`,*可選*) — 畫素解碼器模型最後一階段的最後一個隱藏狀態(最終特徵圖)。
  • `transformer_decoder_last_hidden_state` (`tuple(torch.FloatTensor)`) — Transformer 解碼器的最終輸出 `(batch_size, sequence_length, hidden_size)`。
  • encoder_hidden_states (tuple(torch.FloatTensor), 可選) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。編碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), , 可選,當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。畫素解碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可選) — 形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。Transformer 解碼器在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。
  • transformer_decoder_intermediate_states (形狀為 (num_queries, 1, hidden_size)tuple(torch.FloatTensor)) — 中間解碼器啟用,即每個解碼器層的輸出,每個輸出都經過了層歸一化。
  • masks_queries_logits (形狀為 (batch_size, num_queries, height, width)tuple(torch.FloatTensor)) — Transformer 解碼器中每個層的掩碼預測。
  • attentions (tuple(tuple(torch.FloatTensor)), 可選,當傳入 output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)tuple(torch.FloatTensor) 元組(每個層一個)。Transformer 解碼器的自注意力權重。
  • attentions (tuple[torch.FloatTensor], 可選,當傳入 output_attentions=Trueconfig.output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元組(每個層一個)。

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

Mask2FormerModel 的輸出類。此類別返回計算 logits 所需的所有隱藏狀態。

class transformers.models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput

< >

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

引數

  • loss (torch.Tensor, 可選) — 計算出的損失,當存在標籤時返回。
  • class_queries_logits (torch.FloatTensor, 可選, 預設為 None) — 形狀為 (batch_size, num_queries, num_labels + 1) 的張量,表示每個查詢的建議類別。請注意,需要 + 1 是因為我們包含了空類別。
  • masks_queries_logits (torch.FloatTensor, 可選, 預設為 None) — 形狀為 (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) — 編碼器模型(主幹)最後一階段的最後隱藏狀態(最終特徵圖)。
  • pixel_decoder_last_hidden_state (形狀為 (batch_size, num_channels, height, width)torch.FloatTensor) — 畫素解碼器模型最後一階段的最後隱藏狀態(最終特徵圖)。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — Transformer 解碼器的最終輸出 (batch_size, sequence_length, hidden_size)
  • encoder_hidden_states (tuple(torch.FloatTensor), 可選,當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。編碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), 可選,當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。畫素解碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可選,當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — 形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。Transformer 解碼器在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • attentions (tuple(tuple(torch.FloatTensor)), 可選,當傳入 output_attentions=Trueconfig.output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)tuple(torch.FloatTensor) 元組(每個層一個)。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 模型,直接輸出原始隱藏狀態,不帶任何特定頭部。

此模型繼承自 PreTrainedModel。請檢視父類文件,瞭解該庫為所有模型實現的所有通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件以瞭解所有與一般用法和行為相關的事項。

前向傳播

< >

( 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.Mask2FormerModelOutput or tuple(torch.FloatTensor)

引數

  • pixel_values (形狀為 (batch_size, num_channels, image_size, image_size)torch.Tensor) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • pixel_mask (形狀為 (batch_size, height, width)torch.Tensor, 可選) — 用於避免對填充畫素值執行注意力的掩碼。掩碼值選擇在 [0, 1] 之間:

    • 1 表示真實畫素(即未被遮蔽),
    • 0 表示填充畫素(即被遮蔽)。

    什麼是注意力掩碼?

  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通的元組。

返回

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

一個 transformers.models.mask2former.modeling_mask2former.Mask2FormerModelOutput 或一個 torch.FloatTensor 元組(如果傳入 return_dict=Falseconfig.return_dict=False),包含各種元素,具體取決於配置(Mask2FormerConfig)和輸入。

  • encoder_last_hidden_state (形狀為 (batch_size, num_channels, height, width)torch.FloatTensor, 可選) — 編碼器模型(主幹)最後一階段的最後隱藏狀態(最終特徵圖)。當傳入 output_hidden_states=True 時返回。

  • pixel_decoder_last_hidden_state (形狀為 (batch_size, num_channels, height, width)torch.FloatTensor, 可選) — 畫素解碼器模型最後一階段的最後隱藏狀態(最終特徵圖)。

  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — Transformer 解碼器的最終輸出 (batch_size, sequence_length, hidden_size)

  • encoder_hidden_states (tuple(torch.FloatTensor), 可選) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。編碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。

  • pixel_decoder_hidden_states (tuple(torch.FloatTensor), , 可選,當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。畫素解碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。

  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可選) — 形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出)。Transformer 解碼器在每個階段輸出的隱藏狀態(也稱為特徵圖)。當傳入 output_hidden_states=True 時返回。

  • transformer_decoder_intermediate_states (形狀為 (num_queries, 1, hidden_size)tuple(torch.FloatTensor)) — 中間解碼器啟用,即每個解碼器層的輸出,每個輸出都經過了層歸一化。

  • masks_queries_logits (形狀為 (batch_size, num_queries, height, width)tuple(torch.FloatTensor)) Transformer 解碼器中每個層的掩碼預測。

  • attentions (tuple(tuple(torch.FloatTensor)), 可選,當傳入 output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)tuple(torch.FloatTensor) 元組(每個層一個)。Transformer 解碼器的自注意力權重。

  • attentions (tuple[torch.FloatTensor], 可選,當傳入 output_attentions=Trueconfig.output_attentions=True 時返回) — 形狀為 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元組(每個層一個)。

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

Mask2FormerModel 的前向傳播方法,覆蓋了 __call__ 特殊方法。

儘管前向傳播的實現需要在該函式中定義,但隨後應該呼叫 Module 例項而不是直接呼叫此函式,因為前者負責執行預處理和後處理步驟,而後者會靜默忽略它們。

Mask2FormerForUniversalSegmentation

class transformers.Mask2FormerForUniversalSegmentation

< >

( config: Mask2FormerConfig )

引數

  • config (Mask2FormerConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法以載入模型權重。

帶頭部(用於例項/語義/全景分割)的 Mask2Former 模型。

此模型繼承自 PreTrainedModel。請檢視父類文件,瞭解該庫為所有模型實現的所有通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件以瞭解所有與一般用法和行為相關的事項。

前向傳播

< >

( pixel_values: Tensor mask_labels: typing.Optional[list[torch.Tensor]] = None class_labels: typing.Optional[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.Mask2FormerForUniversalSegmentationOutput or tuple(torch.FloatTensor)

引數

  • pixel_values (形狀為 (batch_size, num_channels, image_size, image_size)torch.Tensor) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • 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] 的標籤。
  • pixel_mask (形狀為 (batch_size, height, width)torch.Tensor, 可選) — 用於避免對填充畫素值執行注意力的掩碼。掩碼值選擇在 [0, 1] 之間:

    • 1 表示真實畫素(即未被遮蔽),
    • 0 表示填充畫素(即被遮蔽)。

    什麼是注意力掩碼?

  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • output_auxiliary_logits (bool, 可選) — 是否輸出輔助 logits。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通的元組。

返回

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可選,預設為 None) — 形狀為 (batch_size, num_queries, num_labels + 1) 的張量,表示每個查詢的建議類別。請注意需要 + 1 是因為我們加入了空類別。
  • masks_queries_logits (torch.FloatTensor, 可選, 預設為 None) — 形狀為 (batch_size, num_queries, height, width) 的張量,表示每個查詢的建議掩碼。
  • auxiliary_logits (list[Dict(str, torch.FloatTensor)]可選) — 變壓器解碼器每一層輸出的類別和掩碼預測列表。
  • encoder_last_hidden_state (形狀為 (batch_size, num_channels, height, width)torch.FloatTensor) — 編碼器模型(骨幹網路)最後一階段的最後隱藏狀態(最終特徵圖)。
  • pixel_decoder_last_hidden_state (形狀為 (batch_size, num_channels, height, width)torch.FloatTensor) — 畫素解碼器模型最後一階段的最後隱藏狀態(最終特徵圖)。
  • transformer_decoder_last_hidden_state (tuple(torch.FloatTensor)) — Transformer 解碼器的最終輸出 (batch_size, sequence_length, hidden_size)
  • encoder_hidden_states (tuple(torch.FloatTensor)可選,當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出),形狀為 (batch_size, num_channels, height, width)。編碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • pixel_decoder_hidden_states (tuple(torch.FloatTensor)可選,當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出),形狀為 (batch_size, num_channels, height, width)。畫素解碼器模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor)可選,當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層輸出 + 一個用於每個階段的輸出),形狀為 (batch_size, sequence_length, hidden_size)。變壓器解碼器在每個階段輸出的隱藏狀態(也稱為特徵圖)。
  • attentions (tuple(tuple(torch.FloatTensor))可選,當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — tuple(torch.FloatTensor) 元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)。變壓器解碼器中的自注意和交叉注意權重。

Mask2FormerForUniversalSegmentation 的前向方法,覆蓋了 __call__ 特殊方法。

儘管前向傳播的實現需要在該函式中定義,但隨後應該呼叫 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.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = 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 時有效。如果大小是像 (width, height) 這樣的序列,則輸出大小將匹配此序列。如果大小是整數,則影像的較短邊將匹配此數字。例如,如果 height > width,則影像將被重新縮放為 (size * height / width, size)
  • size_divisor (int可選,預設為 32) — 某些骨幹網路需要影像可被特定數字整除。如果未傳遞,則預設為 Swin Transformer 中使用的值。
  • resample (int可選,預設為 Resampling.BILINEAR) — 可選的重取樣濾波器。可以是 PIL.Image.Resampling.NEARESTPIL.Image.Resampling.BOXPIL.Image.Resampling.BILINEARPIL.Image.Resampling.HAMMINGPIL.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可選) — 分割圖中分配給背景畫素的標籤。如果提供,將用 ignore_index 替換標記為 0(背景)的分割影像素。
  • 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[dict[int, int]] = None do_resize: typing.Optional[bool] = None size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, 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 )

編碼輸入

< 原始檔 >

( pixel_values_list: list 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[list[dict[int, int]], 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可選) — 如果設定,將返回張量而不是 NumPy 陣列。如果設定為 'pt',則返回 PyTorch torch.Tensor 物件。
  • input_data_format (ChannelDimensionstr可選) — 輸入影像的通道維度格式。如果未提供,則將推斷。

返回

批次特徵

一個具有以下欄位的 BatchFeature

  • pixel_values — 要輸入到模型的畫素值。
  • pixel_mask — 要輸入到模型的畫素掩碼(當 =Truepixel_maskself.model_input_names 中時)。
  • mask_labels — 可選的掩碼標籤列表,形狀為 (labels, height, width),用於輸入到模型(當提供 annotations 時)。
  • class_labels — 可選的類別標籤列表,形狀為 (labels),用於饋送到模型(當提供 annotations 時)。它們標識 mask_labels 的標籤,例如 mask_labels[i][j] 的標籤為 class_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[list[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[list[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 的整數。
    • score — 具有 segment_id 的段的預測分數。

Mask2FormerForUniversalSegmentationOutput 的輸出轉換為例項分割預測。僅支援 PyTorch。如果例項可能重疊,則將 return_coco_annotationreturn_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[set[int]] = None target_sizes: typing.Optional[list[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
    • score — 具有 segment_id 的段的預測分數。

Mask2FormerForUniversalSegmentationOutput 的輸出轉換為影像全景分割預測。僅支援 PyTorch。

< > 在 GitHub 上更新

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