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,一个通过多任务一次训练设计来统一分割的通用图像分割框架。我们首先提出了一种任务条件下的联合训练策略,该策略允许在单个多任务训练过程中,针对每个领域(语义分割、实例分割和全景分割)的真实标签进行训练。其次,我们引入了一个任务标记来根据当前任务对模型进行条件化,使我们的模型具有任务动态性,以支持多任务训练和推理。第三,我们建议在训练期间使用查询-文本对比损失来建立更好的任务间和类别间区分。值得注意的是,尽管 Mask2Former 模型在 ADE20k、CityScapes 和 COCO 上对每个任务都单独训练,并使用了三倍的资源,但我们的单个 OneFormer 模型在所有三个分割任务上的性能都优于专门的 Mask2Former 模型。通过新的 ConvNeXt 和 DiNAT 主干网络,我们观察到更显著的性能提升。我们相信 OneFormer 是使图像分割更加通用和易于访问的重要一步。
下图展示了 OneFormer 的架构。摘自原文。

该模型由 Jitesh Jain 贡献。原始代码可在此处找到。
使用技巧
- OneFormer 在推理时需要两个输入:_图像_和_任务标记_。
- 在训练期间,OneFormer 只使用全景标注。
- 如果要在多个节点组成的分布式环境中训练模型,则应更新
modeling_oneformer.py
中OneFormerLoss
类内的get_num_masks
函数。在多节点训练时,此值应设置为所有节点上目标掩码的平均数量,如原始实现此处所示。 - 可以使用OneFormerProcessor为模型准备输入图像和任务输入,以及可选的模型目标。OneFormerProcessor将OneFormerImageProcessor和CLIPTokenizer封装在一个实例中,以便同时准备图像和编码任务输入。
- 要获得最终分割,根据任务的不同,可以调用post_process_semantic_segmentation()、post_process_instance_segmentation()或post_process_panoptic_segmentation()。所有三个任务都可以使用OneFormerForUniversalSegmentation的输出来解决,全景分割接受一个可选的
label_ids_to_fuse
参数来融合目标对象(例如天空)的实例。
资源
官方 Hugging Face 和社区(🌎 表示)资源列表,帮助您开始使用 OneFormer。
- 有关自定义数据推理 + 微调的演示笔记本可在此处找到。
如果您有兴趣提交资源以供此处收录,请随时发起拉取请求,我们将对其进行审查。理想情况下,资源应展示新内容,而非重复现有资源。
OneFormer 特有输出
类 transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput
< 源 >( 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 transformer_decoder_object_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: typing.Optional[torch.FloatTensor] = None transformer_decoder_class_predictions: typing.Optional[torch.FloatTensor] = None transformer_decoder_auxiliary_predictions: typing.Optional[tuple[dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: typing.Optional[torch.FloatTensor] = None attentions: typing.Optional[tuple[torch.FloatTensor]] = None )
参数
- encoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — 编码器模型在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — 像素解码器模型在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — Transformer 解码器在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - 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 (
Tuple
of Dict ofstr, 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
时返回) — Transformer 解码器的自注意力和交叉注意力权重元组(每个层一个),形状为(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: typing.Optional[torch.FloatTensor] = None masks_queries_logits: typing.Optional[torch.FloatTensor] = None auxiliary_predictions: list = None encoder_hidden_states: typing.Optional[tuple[torch.FloatTensor]] = None pixel_decoder_hidden_states: typing.Optional[list[torch.FloatTensor]] = None transformer_decoder_hidden_states: typing.Optional[torch.FloatTensor] = None transformer_decoder_object_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_contrastive_queries: typing.Optional[torch.FloatTensor] = None transformer_decoder_mask_predictions: typing.Optional[torch.FloatTensor] = None transformer_decoder_class_predictions: typing.Optional[torch.FloatTensor] = None transformer_decoder_auxiliary_predictions: typing.Optional[list[dict[str, torch.FloatTensor]]] = None text_queries: typing.Optional[torch.FloatTensor] = None task_token: typing.Optional[torch.FloatTensor] = None attentions: typing.Optional[tuple[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_predictions (
List
of Dict ofstr, torch.FloatTensor
, 可选) — Transformer 解码器每一层的类别和掩码预测列表。 - encoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — 编码器模型在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - pixel_decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — 像素解码器模型在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - transformer_decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — Transformer 解码器在每个阶段输出的隐藏状态(也称为特征图),形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每个阶段的输出)。 - 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 解码器最后一层的类别预测。 - auxiliary_predictions (
List
of Dict ofstr, 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 解码器的自注意力和交叉注意力权重。
OneFormerForUniversalSegmentationOutput
的输出类。
此输出可以直接传递给 post_process_semantic_segmentation()、post_process_instance_segmentation() 或 post_process_panoptic_segmentation(),具体取决于任务。有关用法详情,请参阅 [`~OneFormerImageProcessor]。
OneFormerConfig
class transformers.OneFormerConfig
< source >( backbone_config: typing.Optional[dict] = None backbone: typing.Optional[str] = None use_pretrained_backbone: bool = False use_timm_backbone: bool = False backbone_kwargs: typing.Optional[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
, 可选, 默认为SwinConfig
) — 主干模型的配置。 - 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
,则不能指定此参数。 - ignore_value (
int
, 可选, 默认为 255) — 计算损失时,GT 标签中要忽略的值。 - num_queries (
int
, 可选, 默认为 150) — 对象查询的数量。 - no_object_weight (
float
, 可选, 默认为 0.1) — 无对象类别预测的权重。 - class_weight (
float
, 可选, 默认为 2.0) — 分类交叉熵损失的权重。 - mask_weight (
float
, 可选, 默认为 5.0) — 二进制交叉熵损失的权重。 - dice_weight (
float
, 可选, 默认为 5.0) — Dice 损失的权重。 - contrastive_weight (
float
, 可选, 默认为 0.5) — 对比损失的权重。 - contrastive_temperature (
float
, 可选, 默认为 0.07) — 用于缩放对比 logits 的初始值。 - 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) — Xavier 均匀初始化的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-05) — 层归一化的 epsilon 值。 - is_training (
bool
, 可选, 默认为False
) — 是否在训练或推理模式下运行。 - use_auxiliary_loss (
bool
, 可选, 默认为True
) — 是否使用 Transformer 解码器的中间预测计算损失。 - output_auxiliary_logits (
bool
, 可选, 默认为True
) — 是否返回 Transformer 解码器的中间预测。 - strides (
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) — 文本编码器中 Transformer 层的数量。 - text_encoder_vocab_size (
int
, 可选, 默认为 49408) — 分词器的词汇量大小。 - text_encoder_proj_layers (
int
, 可选, 默认为 2) — 用于投影文本查询的 MLP 层数。 - text_encoder_n_ctx (
int
, 可选, 默认为 16) — 可学习文本上下文查询的数量。 - conv_dim (
int
, 可选, 默认为 256) — 从主干映射输出的特征图维度。 - mask_dim (
int
, 可选, 默认为 256) — 像素解码器中特征图的维度。 - hidden_dim (
int
, 可选, 默认为 256) — Transformer 解码器中隐藏状态的维度。 - encoder_feedforward_dim (
int
, 可选, 默认为 1024) — 像素解码器中 FFN 层的维度。 - norm (
str
, 可选, 默认为"GN"
) — 归一化类型。 - encoder_layers (
int
, 可选, 默认为 6) — 像素解码器中的层数。 - decoder_layers (
int
, 可选, 默认为 10) — Transformer 解码器中的层数。 - use_task_norm (
bool
, 可选, 默认为True
) — 是否对任务 token 进行归一化。 - num_attention_heads (
int
, 可选, 默认为 8) — 像素和 Transformer 解码器中 Transformer 层中的注意力头数量。 - dropout (
float
, 可选, 默认为 0.1) — 像素和 Transformer 解码器的 Dropout 概率。 - dim_feedforward (
int
, 可选, 默认为 2048) — Transformer 解码器中 FFN 层的维度。 - pre_norm (
bool
, 可选, 默认为False
) — 是否在 Transformer 解码器中注意力层之前对隐藏状态进行归一化。 - enforce_input_proj (
bool
, 可选, 默认为False
) — 是否在 Transformer 解码器中投影隐藏状态。 - query_dec_layers (
int
, 可选, 默认为 2) — 查询 Transformer 中的层数。 - common_stride (
int
, 可选, 默认为 4) — 像素解码器中特征的常用步幅。
这是一个配置类,用于存储 OneFormerModel 的配置。它用于根据指定参数实例化 OneFormer 模型,定义模型架构。使用默认值实例化配置将产生与 OneFormer shi-labs/oneformer_ade20k_swin_tiny 在 ADE20k-150 上训练的架构类似的配置。
配置对象继承自 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
class transformers.OneFormerImageProcessor
< source >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None 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 repo_path: typing.Optional[str] = 'shi-labs/oneformer_demo' class_info_file: typing.Optional[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
时生效。如果大小是一个序列,如(width, height)
,则输出大小将与此匹配。如果大小是一个整数,图像较短的边将与此数字匹配。即,如果height > width
,则图像将被重新缩放为(size * height / width, size)
。 - resample (
int
, 可选, 默认为Resampling.BILINEAR
) — 可选的重采样过滤器。可以是PIL.Image.Resampling.NEAREST
,PIL.Image.Resampling.BOX
,PIL.Image.Resampling.BILINEAR
,PIL.Image.Resampling.HAMMING
,PIL.Image.Resampling.BICUBIC
或PIL.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
替换。 - repo_path (
str
, 可选, 默认为"shi-labs/oneformer_demo"
) — 指向包含数据集类信息的 JSON 文件的 hub 仓库或本地目录路径。如果未设置,将在当前工作目录中查找class_info_file
。 - class_info_file (
str
, 可选) — 包含数据集类信息的 JSON 文件。例如,请参阅shi-labs/oneformer_demo/cityscapes_panoptic.json
。 - num_text (
int
, 可选) — 文本输入列表中的文本条目数量。 - num_labels (
int
, 可选) — 分割图中的标签数量。
构建一个 OneFormer 图像处理器。该图像处理器可用于为模型准备图像、任务输入和可选的文本输入及目标。
此图像处理器继承自 BaseImageProcessor,其中包含大部分主要方法。用户应参阅此超类以获取有关这些方法的更多信息。
预处理
< 源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] task_inputs: typing.Optional[list[str]] = None 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 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 task_inputs: 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]
) — 要填充的图像(像素值)列表。每个图像都应该是形状为(通道, 高度, 宽度)
的张量。 - task_inputs (
list[str]
) — 任务值列表。 - 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 (
str
或 TensorType, 可选) — 如果设置,将返回张量而不是 NumPy 数组。如果设置为'pt'
,则返回 PyTorchtorch.Tensor
对象。 - input_data_format (
str
或ChannelDimension
, 可选) — 输入图像的通道维度格式。如果未提供,将从输入图像推断。
返回
一个具有以下字段的 BatchFeature
- pixel_values — 要输入到模型的像素值。
- pixel_mask — 要输入到模型的像素掩码(当
=True
或pixel_mask
在self.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]
,即每个掩码的标签。
后处理语义分割
< 源 >( outputs target_sizes: typing.Optional[list[tuple[int, int]]] = None ) → list[torch.Tensor]
参数
- outputs (MaskFormerForInstanceSegmentation) — 模型的原始输出。
- target_sizes (
list[tuple[int, int]]
, 可选) — 长度为 (batch_size) 的列表,其中每个列表项 (tuple[int, int]]
) 对应于每个预测的请求最终大小(高度,宽度)。如果留空,则不会调整预测大小。
返回
list[torch.Tensor]
一个长度为 batch_size
的列表,其中每个项目是形状为 (高度, 宽度) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MaskFormerForInstanceSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
后处理实例分割
< 源 >( 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[list[tuple[int, int]]] = None return_coco_annotation: typing.Optional[bool] = False ) → list[Dict]
参数
- outputs (
OneFormerForUniversalSegmentationOutput
) —OneFormerForUniversalSegmentationOutput
的输出。 - task_type (
str
, 可选, 默认为“instance”) — 后处理取决于任务令牌输入。如果task_type
为“全景”,则需要忽略物体预测。 - is_demo (
bool
, 可选), 默认为True
) — 模型是否处于演示模式。如果为 True,则使用阈值预测最终掩码。 - 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
) — 是否以 COCO 格式返回预测。
返回
list[Dict]
字典列表,每个图像一个,每个字典包含两个键
- 分割 — 形状为
(height, width)
的张量,其中每个像素表示一个segment_id
,如果没有找到高于threshold
的掩码,则设置为None
。如果指定了target_sizes
,分割将调整为相应的target_sizes
条目。 - segments_info — 包含每个段的附加信息的字典。
- id — 表示
segment_id
的整数。 - label_id — 表示与
segment_id
对应的标签/语义类 ID 的整数。 - was_fused — 一个布尔值,如果
label_id
在label_ids_to_fuse
中则为True
,否则为False
。同一类别/标签的多个实例已融合并分配了一个单独的segment_id
。 - score — 具有
segment_id
的段的预测分数。
- id — 表示
将 OneFormerForUniversalSegmentationOutput
的输出转换为图像实例分割预测。仅支持 PyTorch。
后处理全景分割
< 源 >( 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 (MaskFormerForInstanceSegmentation) — MaskFormerForInstanceSegmentation 的输出。
- 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]
字典列表,每个图像一个,每个字典包含两个键
- 分割 — 形状为
(height, width)
的张量,其中每个像素表示一个segment_id
,如果没有找到高于threshold
的掩码,则设置为None
。如果指定了target_sizes
,分割将调整为相应的target_sizes
条目。 - segments_info — 包含每个段的附加信息的字典。
- id — 表示
segment_id
的整数。 - label_id — 表示与
segment_id
对应的标签/语义类 ID 的整数。 - was_fused — 一个布尔值,如果
label_id
在label_ids_to_fuse
中则为True
,否则为False
。同一类别/标签的多个实例已融合并分配了一个单独的segment_id
。 - score — 具有
segment_id
的段的预测分数。
- id — 表示
将 MaskFormerForInstanceSegmentationOutput
的输出转换为图像全景分割预测。仅支持 PyTorch。
OneFormerProcessor
class transformers.OneFormerProcessor
< 源 >( image_processor = None tokenizer = None max_seq_length: int = 77 task_seq_length: int = 77 **kwargs )
参数
- image_processor (OneFormerImageProcessor) — 图像处理器是必需输入。
- tokenizer ([
CLIPTokenizer
,CLIPTokenizerFast
]) — 分词器是必需输入。 - max_seq_len (
int
, 可选, 默认为 77)) — 输入文本列表的序列长度。 - task_seq_len (
int
, 可选, 默认为 77) — 输入任务令牌的序列长度。
构建一个 OneFormer 处理器,该处理器封装了 OneFormerImageProcessor 和 CLIPTokenizer/CLIPTokenizerFast,使其成为一个继承图像处理器和分词器功能的单一处理器。
此方法将其所有参数转发给 OneFormerImageProcessor.encode_inputs(),然后对 task_inputs 进行分词。有关此方法的更多信息,请参阅其文档字符串。
此方法将其所有参数转发给 OneFormerImageProcessor.post_process_instance_segmentation()。有关此方法的更多信息,请参阅其文档字符串。
此方法将其所有参数转发给 OneFormerImageProcessor.post_process_panoptic_segmentation()。有关此方法的更多信息,请参阅其文档字符串。
此方法将其所有参数转发给 OneFormerImageProcessor.post_process_semantic_segmentation()。有关此方法的更多信息,请参阅其文档字符串。
OneFormerModel
class transformers.OneFormerModel
< 源 >( config: OneFormerConfig )
参数
- config (OneFormerConfig) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型相关的权重,只会加载配置。要加载模型权重,请查看from_pretrained()方法。
不带任何特定头部输出原始隐藏状态的裸 Oneformer 模型。
此模型继承自PreTrainedModel。请查阅超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.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.OneFormerModelOutput 或 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}
处理图像)。 - task_inputs (形状为
(batch_size, sequence_length)
的torch.FloatTensor
) — 任务输入。任务输入可以使用 AutoImageProcessor 获取。有关详细信息,请参阅OneFormerProcessor.__call__()
。 - text_inputs (
list[torch.Tensor]
, 可选) — 形状为(num_queries, sequence_length)
的张量,用于馈送到模型中。 - 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.oneformer.modeling_oneformer.OneFormerModelOutput 或 tuple(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 (形状为
(batch_size, num_queries, hidden_dim)
的torch.FloatTensor
) — transformer 解码器最后一层的输出对象查询。 - transformer_decoder_contrastive_queries (形状为
(batch_size, num_queries, hidden_dim)
的torch.FloatTensor
) — transformer 解码器的对比查询。 - transformer_decoder_mask_predictions (形状为
(batch_size, num_queries, height, width)
的torch.FloatTensor
) — transformer 解码器最后一层的掩码预测。 - transformer_decoder_class_predictions (形状为
(batch_size, num_queries, num_classes+1)
的torch.FloatTensor
) — transformer 解码器最后一层的类别预测。 - transformer_decoder_auxiliary_predictions (
Tuple
of Dict ofstr, torch.FloatTensor
, 可选) — transformer 解码器每一层的类别和掩码预测元组。 - text_queries (
torch.FloatTensor
, 可选, 形状为(batch_size, num_queries, hidden_dim)
) — 从输入文本列表派生的文本查询,用于训练期间计算对比损失。 - task_token (形状为
(batch_size, hidden_dim)
的torch.FloatTensor
) — 用于条件化查询的一维任务令牌。 - attentions (
tuple(tuple(torch.FloatTensor))
, 可选, 当传入output_attentions=True
或config.output_attentions=True
时返回) —tuple(torch.FloatTensor)
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。来自 transformer 解码器的自注意力和交叉注意力权重。
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
class transformers.OneFormerForUniversalSegmentation
< 源 >( config: OneFormerConfig )
参数
- config (OneFormerConfig) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型相关的权重,只会加载配置。要加载模型权重,请查看from_pretrained()方法。
用于实例、语义和全景图像分割的 OneFormer 模型。
此模型继承自PreTrainedModel。请查阅超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般用法和行为相关的事项。
正向传播
< 源 >( pixel_values: Tensor task_inputs: Tensor text_inputs: typing.Optional[torch.Tensor] = None mask_labels: typing.Optional[list[torch.Tensor]] = None class_labels: typing.Optional[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.OneFormerForUniversalSegmentationOutput 或 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}
处理图像)。 - task_inputs (形状为
(batch_size, sequence_length)
的torch.FloatTensor
) — 任务输入。任务输入可以使用 AutoImageProcessor 获取。有关详细信息,请参阅OneFormerProcessor.__call__()
。 - text_inputs (
list[torch.Tensor]
, 可选) — 形状为(num_queries, sequence_length)
的张量,用于馈送到模型。 - mask_labels (
list[torch.Tensor]
, 可选) — 形状为(num_labels, height, width)
的掩码标签列表,用于馈送到模型中。 - class_labels (
list[torch.LongTensor]
, 可选) — 形状为(num_labels, height, width)
的目标类别标签列表,用于馈送到模型中。它们标识了mask_labels
的标签,例如mask_labels[i][j]
的标签为class_labels[i][j]
。 - pixel_mask (形状为
(batch_size, height, width)
的torch.Tensor
, 可选) — 避免对填充像素值执行注意力操作的掩码。掩码值选择在[0, 1]
之间:- 1 表示真实像素(即未被掩盖),
- 0 表示填充像素(即被掩盖)。
- output_auxiliary_logits (
bool
, 可选) — 是否输出辅助 logits。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states
。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而非纯元组。
返回
transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput 或 tuple(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
, 可选, 默认为None
) — 形状为(batch_size, num_queries, num_labels + 1)
的张量,表示每个查询的建议类别。注意,由于我们包含了空类,因此需要+ 1
。 - masks_queries_logits (
torch.FloatTensor
, 可选, 默认为None
) — 形状为(batch_size, num_queries, height, width)
的张量,表示每个查询的建议掩码。 - auxiliary_predictions (
List
of Dict ofstr, torch.FloatTensor
, 可选) — transformer 解码器每一层的类别和掩码预测列表。 - 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 (形状为
(batch_size, num_queries, hidden_dim)
的torch.FloatTensor
) — transformer 解码器最后一层的输出对象查询。 - transformer_decoder_contrastive_queries (形状为
(batch_size, num_queries, hidden_dim)
的torch.FloatTensor
) — transformer 解码器的对比查询。 - transformer_decoder_mask_predictions (形状为
(batch_size, num_queries, height, width)
的torch.FloatTensor
) — transformer 解码器最后一层的掩码预测。 - transformer_decoder_class_predictions (形状为
(batch_size, num_queries, num_classes+1)
的torch.FloatTensor
) — transformer 解码器最后一层的类别预测。 - transformer_decoder_auxiliary_predictions (
List
of Dict ofstr, torch.FloatTensor
, 可选) — transformer 解码器每一层的类别和掩码预测列表。 - text_queries (
torch.FloatTensor
, 可选, 形状为(batch_size, num_queries, hidden_dim)
) — 从输入文本列表派生的文本查询,用于训练期间计算对比损失。 - task_token (形状为
(batch_size, hidden_dim)
的torch.FloatTensor
) — 用于条件化查询的一维任务令牌。 - attentions (
tuple(tuple(torch.FloatTensor))
, 可选, 当传入output_attentions=True
或config.output_attentions=True
时返回) —tuple(torch.FloatTensor)
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。来自 transformer 解码器的自注意力和交叉注意力权重。
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]'