Transformers 文档

OneFormer

OneFormer

概述

OneFormer模型由Jitesh Jain、Jiachen Li、MangTik Chiu、Ali Hassani、Nikita Orlov和Humphrey Shi在OneFormer: One Transformer to Rule Universal Image Segmentation中提出。OneFormer是一个通用的图像分割框架,可以在单一的全景数据集上进行训练,以执行语义、实例和全景分割任务。OneFormer使用任务令牌来根据当前任务调整模型,使得架构在训练时是任务引导的,在推理时是任务动态的。

论文的摘要如下:

通用图像分割并不是一个新概念。过去几十年中,统一图像分割的尝试包括场景解析、全景分割,以及最近的新全景架构。然而,这些全景架构并没有真正统一图像分割,因为它们需要在语义、实例或全景分割上单独训练才能达到最佳性能。理想情况下,一个真正通用的框架应该只需训练一次,并在所有三种图像分割任务中实现SOTA性能。为此,我们提出了OneFormer,一个通过多任务一次性训练设计统一分割的通用图像分割框架。我们首先提出了一种任务条件联合训练策略,使得在单个多任务训练过程中能够对每个领域(语义、实例和全景分割)的真实数据进行训练。其次,我们引入了一个任务标记来根据当前任务调整我们的模型,使我们的模型具有任务动态性,以支持多任务训练和推理。第三,我们提出在训练过程中使用查询文本对比损失,以建立更好的任务间和类别间区分。值得注意的是,我们的单一OneFormer模型在ADE20k、CityScapes和COCO上的所有三种分割任务中均优于专门的Mask2Former模型,尽管后者在每种任务上分别训练并使用了三倍的资源。通过新的ConvNeXt和DiNAT骨干网络,我们观察到更多的性能提升。我们相信OneFormer是使图像分割更加通用和易于访问的重要一步。

下图展示了OneFormer的架构。取自原始论文

该模型由Jitesh Jain贡献。原始代码可以在这里找到。

使用提示

资源

一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用OneFormer。

  • 关于在自定义数据上进行推理和微调的演示笔记本可以在这里找到。

如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将对其进行审查。 理想情况下,资源应展示一些新的内容,而不是重复现有的资源。

OneFormer 特定输出

transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput

< >

( 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 transformer_decoder_object_queries: FloatTensor = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: FloatTensor = None transformer_decoder_class_predictions: FloatTensor = None transformer_decoder_auxiliary_predictions: typing.Optional[typing.Tuple[typing.Dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: FloatTensor = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

参数

  • 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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出 + 每个阶段的输出)的形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出 + 一个用于每个阶段的输出)的形状为 (batch_size, sequence_length, hidden_size)。Transformer解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor of shape (batch_size, num_queries, hidden_dim)) — 从transformer解码器的最后一层输出的对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor of shape (batch_size, num_queries, hidden_dim)) — 来自变压器解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor of shape (batch_size, num_queries, height, width)) — 来自transformer解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor of shape (batch_size, num_queries, num_classes+1)) — Transformer解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (Tuple of Dict of str, torch.FloatTensor, optional) — Transformer解码器每一层的类别和掩码预测的元组。
  • text_queries (torch.FloatTensor, optional of shape (batch_size, num_queries, hidden_dim)) — 从输入文本列表中派生的文本查询,用于在训练期间计算对比损失。
  • task_token (torch.FloatTensor of shape (batch_size, hidden_dim)) — 1D任务令牌用于条件化查询。
  • 注意力 (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — tuple(torch.FloatTensor) 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自变压器解码器的自注意力和交叉注意力权重。

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

transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None class_queries_logits: FloatTensor = None masks_queries_logits: FloatTensor = None auxiliary_predictions: typing.List[typing.Dict[str, torch.FloatTensor]] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[typing.List[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = None transformer_decoder_object_queries: FloatTensor = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: FloatTensor = None transformer_decoder_class_predictions: FloatTensor = None transformer_decoder_auxiliary_predictions: typing.Optional[typing.List[typing.Dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: FloatTensor = None attentions: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None )

参数

  • loss (torch.Tensor, optional) — 计算得到的损失,当存在标签时返回。
  • 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_predictions (List of Dict of str, torch.FloatTensor, optional) — 来自变压器解码器每一层的类别和掩码预测列表。
  • 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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出 + 每个阶段的输出)的形状为 (batch_size, num_channels, height, width)。像素解码器模型在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出 + 每个阶段的输出)的形状为 (batch_size, sequence_length, hidden_size)。每个阶段输出的 transformer 解码器的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor of shape (batch_size, num_queries, hidden_dim)) — 从transformer解码器的最后一层输出的对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor of shape (batch_size, num_queries, hidden_dim)) — 来自变压器解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor of shape (batch_size, num_queries, height, width)) — 来自transformer解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor of shape (batch_size, num_queries, num_classes+1)) — Transformer解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (List of Dict of str, torch.FloatTensor, optional) — 来自transformer解码器每一层的类别和掩码预测列表。
  • text_queries (torch.FloatTensor, 可选,形状为 (batch_size, num_queries, hidden_dim)) — 从输入文本列表中派生的文本查询,用于在训练期间计算对比损失。
  • task_token (torch.FloatTensor of shape (batch_size, hidden_dim)) — 1D任务令牌用于条件化查询。
  • 注意力 (tuple(tuple(torch.FloatTensor)), 可选, 当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)tuple(tuple(torch.FloatTensor)) 元组(每层一个)。来自变压器解码器的自注意力和交叉注意力权重。

用于OneFormerForUniversalSegmentationOutput输出的类。

此输出可以直接传递给 post_process_semantic_segmentation()post_process_instance_segmentation()post_process_panoptic_segmentation(),具体取决于任务。请参阅 [`~OneFormerImageProcessor] 了解使用详情。

OneFormerConfig

transformers.OneFormerConfig

< >

( backbone_config: typing.Optional[typing.Dict] = None backbone: typing.Optional[str] = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: typing.Optional[typing.Dict] = None ignore_value: int = 255 num_queries: int = 150 no_object_weight: int = 0.1 class_weight: float = 2.0 mask_weight: float = 5.0 dice_weight: float = 5.0 contrastive_weight: float = 0.5 contrastive_temperature: float = 0.07 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 layer_norm_eps: float = 1e-05 is_training: bool = False use_auxiliary_loss: bool = True output_auxiliary_logits: bool = True strides: typing.Optional[list] = [4, 8, 16, 32] task_seq_len: int = 77 text_encoder_width: int = 256 text_encoder_context_length: int = 77 text_encoder_num_layers: int = 6 text_encoder_vocab_size: int = 49408 text_encoder_proj_layers: int = 2 text_encoder_n_ctx: int = 16 conv_dim: int = 256 mask_dim: int = 256 hidden_dim: int = 256 encoder_feedforward_dim: int = 1024 norm: str = 'GN' encoder_layers: int = 6 decoder_layers: int = 10 use_task_norm: bool = True num_attention_heads: int = 8 dropout: float = 0.1 dim_feedforward: int = 2048 pre_norm: bool = False enforce_input_proj: bool = False query_dec_layers: int = 2 common_stride: int = 4 **kwargs )

参数

  • backbone_config (PretrainedConfig, optional, defaults to SwinConfig) — 骨干模型的配置。
  • backbone (str, 可选) — 当 backbone_configNone 时使用的骨干网络名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载骨干网络的配置并使用该配置初始化具有随机权重的骨干网络。
  • use_pretrained_backbone (bool, 可选, 默认为 False) — 是否使用预训练的权重作为骨干网络。
  • use_timm_backbone (bool, optional, defaults to False) — 是否从timm库加载backbone。如果为False,则从transformers库加载backbone。
  • backbone_kwargs (dict, 可选) — 从检查点加载时传递给AutoBackbone的关键字参数 例如 {'out_indices': (0, 1, 2, 3)}。如果设置了backbone_config,则不能指定此参数。
  • ignore_value (int, optional, defaults to 255) — 在计算损失时,GT标签中要忽略的值。
  • num_queries (int, 可选, 默认为 150) — 对象查询的数量.
  • no_object_weight (float, optional, 默认为 0.1) — 无对象类预测的权重。
  • class_weight (float, 可选, 默认为 2.0) — 分类交叉熵损失的权重。
  • mask_weight (float, optional, defaults to 5.0) — 二元交叉熵损失的权重。
  • dice_weight (float, optional, defaults to 5.0) — Dice损失的权重。
  • contrastive_weight (float, optional, defaults to 0.5) — 对比损失的权重。
  • contrastive_temperature (float, optional, 默认为 0.07) — 用于缩放对比对数初始值。
  • train_num_points (int, optional, defaults to 12544) — 在计算掩码预测损失时采样的点数。
  • oversample_ratio (float, optional, defaults to 3.0) — 决定要过采样多少点的比率。
  • importance_sample_ratio (float, optional, defaults to 0.75) — 通过重要性采样采样的点的比例。
  • init_std (float, optional, defaults to 0.02) — 用于正态初始化的标准差.
  • init_xavier_std (float, optional, defaults to 1.0) — 用于xavier均匀初始化的标准差.
  • layer_norm_eps (float, optional, defaults to 1e-05) — 层归一化的Epsilon值.
  • is_training (bool, 可选, 默认为 False) — 是否在训练或推理模式下运行。
  • use_auxiliary_loss (bool, optional, defaults to True) — 是否使用来自transformer解码器的中间预测来计算损失。
  • output_auxiliary_logits (bool, optional, defaults to True) — 是否返回来自transformer解码器的中间预测。
  • strides (list, optional, defaults to [4, 8, 16, 32]) — 包含编码器中特征图步幅的列表。
  • task_seq_len (int, optional, defaults to 77) — 用于标记化文本列表输入的序列长度。
  • text_encoder_width (int, optional, 默认为 256) — 文本编码器的隐藏大小。
  • text_encoder_context_length (int, optional, 默认为 77) — 文本编码器的输入序列长度。
  • text_encoder_num_layers (int, optional, defaults to 6) — 文本编码器中变压器的层数。
  • text_encoder_vocab_size (int, optional, defaults to 49408) — 分词器的词汇表大小。
  • text_encoder_proj_layers (int, optional, defaults to 2) — 用于投影文本查询的MLP层数。
  • text_encoder_n_ctx (int, optional, 默认为 16) — 可学习的文本上下文查询的数量。
  • conv_dim (int, 可选, 默认为 256) — 特征图维度,用于映射来自主干的输出。
  • mask_dim (int, optional, defaults to 256) — 像素解码器中特征图的维度。
  • hidden_dim (int, optional, defaults to 256) — Transformer解码器中隐藏状态的维度。
  • encoder_feedforward_dim (int, optional, defaults to 1024) — 像素解码器中FFN层的维度。
  • norm (str, optional, defaults to "GN") — 归一化类型.
  • encoder_layers (int, optional, defaults to 6) — 像素解码器中的层数。
  • decoder_layers (int, optional, defaults to 10) — Transformer解码器中的层数。
  • use_task_norm (bool, 可选, 默认为 True) — 是否对任务令牌进行归一化。
  • num_attention_heads (int, optional, defaults to 8) — 在像素和变压器解码器中的变压器层中的注意力头数。
  • dropout (float, optional, defaults to 0.1) — 像素和变压器解码器的丢弃概率。
  • dim_feedforward (int, optional, defaults to 2048) — Transformer解码器中FFN层的维度。
  • pre_norm (bool, optional, defaults to False) — 是否在transformer解码器的注意力层之前对隐藏状态进行归一化。
  • enforce_input_proj (bool, 可选, 默认为 False) — 是否在变压器解码器中投影隐藏状态。
  • query_dec_layers (int, optional, defaults to 2) — 查询变换器中的层数。
  • common_stride (int, optional, defaults to 4) — 像素解码器中用于特征的常见步幅。

这是用于存储OneFormerModel配置的配置类。它用于根据指定的参数实例化一个OneFormer模型,定义模型架构。使用默认值实例化配置将产生类似于在ADE20k-150上训练的shi-labs/oneformer_ade20k_swin_tiny架构的配置。

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

示例:

>>> from transformers import OneFormerConfig, OneFormerModel

>>> # Initializing a OneFormer shi-labs/oneformer_ade20k_swin_tiny configuration
>>> configuration = OneFormerConfig()
>>> # Initializing a model (with random weights) from the shi-labs/oneformer_ade20k_swin_tiny style configuration
>>> model = OneFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config

OneFormerImageProcessor

transformers.OneFormerImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = 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 repo_path: typing.Optional[str] = 'shi-labs/oneformer_demo' class_info_file: str = None num_text: typing.Optional[int] = None 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).
  • resample (int, optional, defaults to 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, optional, defaults to True) — 是否使用均值和标准差对输入进行归一化。
  • image_mean (int, optional, defaults to [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.
  • repo_path (str, optional, defaults to "shi-labs/oneformer_demo") — 包含数据集类别信息的JSON文件的hub仓库路径或本地目录路径。 如果未设置,将在当前工作目录中查找class_info_file
  • class_info_file (str, optional) — 包含数据集类别信息的JSON文件。参见 shi-labs/oneformer_demo/cityscapes_panoptic.json 作为示例。
  • num_text (int, optional) — 文本输入列表中的文本条目数量。
  • num_labels (int, optional) — 分割图中的标签数量。

构建一个OneFormer图像处理器。该图像处理器可用于准备图像、任务输入以及可选的文本输入和目标,以供模型使用。

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

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] task_inputs: typing.Optional[typing.List[str]] = None segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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 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] = 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'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]]] task_inputs: typing.List[str] segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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) 的张量。
  • task_inputs (List[str]) — 任务值列表.
  • segmentation_maps (ImageInput, optional) — The corresponding semantic segmentation maps with the pixel-wise annotations.

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

    如果保留默认设置,将返回一个像素掩码,该掩码是:

    • 1 for pixels that are real (i.e. not masked),
    • 0 for pixels that are padding (i.e. masked).
  • 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 (strChannelDimension, 可选) — 输入图像的通道维度格式。如果未提供,将从输入图像中推断。

返回

BatchFeature

一个包含以下字段的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]
  • text_inputs — 可选的文本字符串条目列表,用于输入模型(当提供annotations时)。它们标识图像中存在的二进制掩码。

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

OneFormer 使用掩码分类范式处理语义分割,因此输入的分割图将被转换为二进制掩码列表及其各自的标签。让我们看一个例子,假设 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]

参数

  • 输出 (MaskFormerForInstanceSegmentation) — 模型的原始输出。
  • 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。

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

post_process_instance_segmentation

< >

( outputs task_type: str = 'instance' is_demo: bool = True 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 ) List[Dict]

参数

  • 输出 (OneFormerForUniversalSegmentationOutput) — 来自 OneFormerForUniversalSegmentationOutput 的输出。
  • task_type (str, optional, 默认为“instance”) — 后处理取决于任务令牌输入。如果 task_type 是“panoptic”,我们需要忽略stuff预测。
  • is_demo (bool, 可选), 默认为 True) — 模型是否处于演示模式。如果为真,则使用阈值来预测最终掩码。
  • threshold (float, optional, defaults to 0.5) — 用于保留预测实例掩码的概率分数阈值。
  • mask_threshold (float, optional, defaults to 0.5) — 用于将预测的掩码转换为二进制值的阈值。
  • overlap_mask_area_threshold (float, optional, defaults to 0.8) — 用于合并或丢弃每个二进制实例掩码中小的不连接部分的重叠掩码区域阈值。
  • target_sizes (List[Tuple], 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (Tuple[int, int]]) 对应于批次中每个预测的请求 最终大小(高度,宽度)。如果留空,预测将不会 调整大小。
  • return_coco_annotation (bool, 可选), 默认为 False) — 是否以COCO格式返回预测结果.

返回

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 的段的预测分数。

OneFormerForUniversalSegmentationOutput的输出转换为图像实例分割预测。仅支持PyTorch。

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]

参数

  • 输出 (MaskFormerForInstanceSegmentationOutput) — 来自 MaskFormerForInstanceSegmentation 的输出.
  • threshold (float, optional, 默认为 0.5) — 用于保留预测实例掩码的概率分数阈值。
  • mask_threshold (float, optional, defaults to 0.5) — 用于将预测的掩码转换为二进制值的阈值。
  • overlap_mask_area_threshold (float, optional, defaults to 0.8) — 用于合并或丢弃每个二进制实例掩码内小断开部分的重叠掩码区域阈值。
  • label_ids_to_fuse (Set[int], 可选) — 此状态中的标签将使其所有实例融合在一起。例如,我们可以说 一张图片中只能有一个天空,但可以有几个人,所以天空的标签ID会在该集合中, 但人的标签ID不会在其中。
  • target_sizes (List[Tuple], optional) — 长度为 (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 的段的预测分数。

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

OneFormerProcessor

transformers.OneFormerProcessor

< >

( image_processor = 无 tokenizer = 无 max_seq_length: int = 77 task_seq_length: int = 77 **kwargs )

参数

  • image_processor (OneFormerImageProcessor) — 图像处理器是一个必需的输入。
  • tokenizer ([CLIPTokenizer, CLIPTokenizerFast]) — tokenizer 是一个必需的输入。
  • max_seq_len (int, optional, defaults to 77)) — 输入文本列表的序列长度。
  • task_seq_len (int, optional, 默认为 77) — 输入任务标记的序列长度。

构建一个OneFormer处理器,它将OneFormerImageProcessorCLIPTokenizer/CLIPTokenizerFast封装成一个单一的处理器,继承了图像处理器和 分词器的功能。

encode_inputs

< >

( images = None task_inputs = None segmentation_maps = None **kwargs )

此方法将其所有参数转发给OneFormerImageProcessor.encode_inputs(),然后对task_inputs进行标记化。请参阅此方法的文档字符串以获取更多信息。

post_process_instance_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发给OneFormerImageProcessor.post_process_instance_segmentation()。 请参阅此方法的文档字符串以获取更多信息。

post_process_panoptic_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发给OneFormerImageProcessor.post_process_panoptic_segmentation()。 请参阅此方法的文档字符串以获取更多信息。

post_process_semantic_segmentation

< >

( *args **kwargs )

此方法将其所有参数转发给OneFormerImageProcessor.post_process_semantic_segmentation()。 请参阅此方法的文档字符串以获取更多信息。

OneFormerModel

transformers.OneFormerModel

< >

( config: OneFormerConfig )

参数

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

裸的OneFormer模型输出原始隐藏状态,没有任何特定的头部。 这个模型是PyTorch nn.Module 的子类。将其用作 常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有事项。

前进

< >

( pixel_values: Tensor task_inputs: Tensor text_inputs: typing.Optional[torch.Tensor] = None 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.oneformer.modeling_oneformer.OneFormerModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用OneFormerProcessor获取。详情请参见 OneFormerProcessor.__call__().
  • task_inputs (torch.FloatTensor of shape (batch_size, sequence_length)) — 任务输入。任务输入可以使用AutoImageProcessor获取。详情请参见OneFormerProcessor.__call__()
  • pixel_mask (torch.LongTensor of shape (batch_size, height, width), optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in [0, 1]:
    • 1 for pixels that are real (i.e. not masked),
    • 0 for pixels that are padding (i.e. masked).

    什么是注意力掩码?

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

返回

transformers.models.oneformer.modeling_oneformer.OneFormerModelOutputtuple(torch.FloatTensor)

一个 transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,取决于配置(OneFormerConfig)和输入。

  • 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)。Transformer 解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor 形状为 (batch_size, num_queries, hidden_dim)) Transformer 解码器最后一层输出的对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor 形状为 (batch_size, num_queries, hidden_dim)) Transformer 解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor 形状为 (batch_size, num_queries, height, width)) Transformer 解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor 形状为 (batch_size, num_queries, num_classes+1)) — Transformer 解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (由 str, torch.FloatTensor 组成的字典元组, 可选) — Transformer 解码器每一层的类别和掩码预测的元组。
  • text_queries (torch.FloatTensor, 可选 形状为 (batch_size, num_queries, hidden_dim)) 从输入文本列表派生的文本查询,用于训练期间计算对比损失。
  • task_token (torch.FloatTensor 形状为 (batch_size, hidden_dim)) 用于条件化查询的一维任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 tuple(torch.FloatTensor) 组成的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。Transformer 解码器的自注意力和交叉注意力权重。

OneFormerModelOutput

OneFormerModel 的前向方法,重写了 __call__ 特殊方法。

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

示例:

>>> import torch
>>> from PIL import Image
>>> import requests
>>> from transformers import OneFormerProcessor, OneFormerModel

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

>>> # load processor for preprocessing the inputs
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerModel.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> inputs = processor(image, ["semantic"], return_tensors="pt")

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

>>> mask_predictions = outputs.transformer_decoder_mask_predictions
>>> class_predictions = outputs.transformer_decoder_class_predictions

>>> f"👉 Mask Predictions Shape: {list(mask_predictions.shape)}, Class Predictions Shape: {list(class_predictions.shape)}"
'👉 Mask Predictions Shape: [1, 150, 128, 171], Class Predictions Shape: [1, 150, 151]'

OneFormerForUniversalSegmentation

transformers.OneFormerForUniversalSegmentation

< >

( config: OneFormerConfig )

参数

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

OneFormer模型用于实例、语义和全景图像分割。 该模型是PyTorch nn.Module的子类。将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: Tensor task_inputs: Tensor text_inputs: typing.Optional[torch.Tensor] = None 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_auxiliary_logits: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用OneFormerProcessor获取。详情请参见 OneFormerProcessor.__call__().
  • task_inputs (torch.FloatTensor of shape (batch_size, sequence_length)) — 任务输入。任务输入可以使用AutoImageProcessor获取。详情请参见OneFormerProcessor.__call__()
  • pixel_mask (torch.LongTensor of shape (batch_size, height, width), optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in [0, 1]:
    • 1 for pixels that are real (i.e. not masked),
    • 0 for pixels that are padding (i.e. masked).

    什么是注意力掩码?

  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • output_attentions (bool, optional) — 是否返回Detr解码器注意力层的注意力张量。
  • return_dict (bool, optional) — 是否返回一个 ~OneFormerModelOutput 而不是一个普通的元组。
  • text_inputs (List[torch.Tensor], optional) — 形状为 (num_queries, sequence_length) 的张量,用于输入模型
  • mask_labels (List[torch.Tensor], optional) — 形状为 (num_labels, height, width) 的掩码标签列表,用于输入模型
  • class_labels (List[torch.LongTensor], optional) — 要输入模型的形状为 (num_labels, height, width) 的目标类别标签列表。它们标识了 mask_labels 的标签,例如如果 class_labels[i][j]mask_labels[i][j] 的标签。

返回

transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutputtuple(torch.FloatTensor)

一个 transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(OneFormerConfig)和输入。

  • 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_predictions (List of Dict of str, torch.FloatTensor, 可选) — 来自变压器解码器每一层的类别和掩码预测列表。
  • 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)。变压器解码器在每个阶段输出的隐藏状态(也称为特征图)。
  • transformer_decoder_object_queries (torch.FloatTensor 形状为 (batch_size, num_queries, hidden_dim)) 来自变压器解码器最后一层的输出对象查询。
  • transformer_decoder_contrastive_queries (torch.FloatTensor 形状为 (batch_size, num_queries, hidden_dim)) 来自变压器解码器的对比查询。
  • transformer_decoder_mask_predictions (torch.FloatTensor 形状为 (batch_size, num_queries, height, width)) 来自变压器解码器最后一层的掩码预测。
  • transformer_decoder_class_predictions (torch.FloatTensor 形状为 (batch_size, num_queries, num_classes+1)) — 来自变压器解码器最后一层的类别预测。
  • transformer_decoder_auxiliary_predictions (List of Dict of str, torch.FloatTensor, 可选) — 来自变压器解码器每一层的类别和掩码预测列表。
  • text_queries (torch.FloatTensor, 可选 形状为 (batch_size, num_queries, hidden_dim)) 从输入文本列表派生的文本查询,用于在训练期间计算对比损失。
  • task_token (torch.FloatTensor 形状为 (batch_size, hidden_dim)) 用于条件化查询的一维任务令牌。
  • attentions (tuple(tuple(torch.FloatTensor)), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 tuple(torch.FloatTensor) 组成的元组(每个层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。来自变压器解码器的自注意力和交叉注意力权重。

OneFormerUniversalSegmentationOutput

OneFormerForUniversalSegmentation 的前向方法,重写了 __call__ 特殊方法。

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

示例:

通用分割示例:

>>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch

>>> # load OneFormer fine-tuned on ADE20k for universal segmentation
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerForUniversalSegmentation.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")

>>> 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)

>>> # Semantic Segmentation
>>> inputs = processor(image, ["semantic"], 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

>>> # you can pass them to processor for semantic postprocessing
>>> predicted_semantic_map = processor.post_process_semantic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> f"👉 Semantic Predictions Shape: {list(predicted_semantic_map.shape)}"
'👉 Semantic Predictions Shape: [512, 683]'

>>> # Instance Segmentation
>>> inputs = processor(image, ["instance"], 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

>>> # you can pass them to processor for instance postprocessing
>>> predicted_instance_map = processor.post_process_instance_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Instance Predictions Shape: {list(predicted_instance_map.shape)}"
'👉 Instance Predictions Shape: [512, 683]'

>>> # Panoptic Segmentation
>>> inputs = processor(image, ["panoptic"], 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

>>> # you can pass them to processor for panoptic postprocessing
>>> predicted_panoptic_map = processor.post_process_panoptic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Panoptic Predictions Shape: {list(predicted_panoptic_map.shape)}"
'👉 Panoptic Predictions Shape: [512, 683]'
< > Update on GitHub