# UPerNet

## 概述

UPerNet 模型由 Tete Xiao、Yingcheng Liu、Bolei Zhou、Yuning Jiang 和 Jian Sun 在 [Unified Perceptual Parsing for Scene Understanding](https://huggingface.co/papers/1807.10221) 中提出。UPerNet 是一个通用框架，能够利用任意视觉骨干网络（如 [ConvNeXt](convnext) 或 [Swin](swin)）从图像中有效地分割出广泛的概念。

该论文的摘要如下：

*人类在多个层面上感知视觉世界：我们能够轻松地对场景进行分类并检测其中的物体，同时还能识别物体的纹理和表面，以及它们不同的组成部分。本文研究了一项名为统一感知解析（Unified Perceptual Parsing）的新任务，该任务要求机器视觉系统从给定图像中识别尽可能多的视觉概念。我们开发了一个名为 UPerNet 的多任务框架以及一种训练策略，以从异构的图像标注中学习。我们在统一感知解析任务上对该框架进行了基准测试，结果表明它能够有效地从图像中分割出广泛的概念。训练好的网络还被进一步应用于发现自然场景中的视觉知识。*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/upernet_architecture.jpg"
alt="drawing" width="600"/>

 UPerNet 框架。摘自原始论文。

该模型由 [nielsr](https://huggingface.co/nielsr) 贡献。原始代码基于 OpenMMLab 的 mmsegmentation，[在此处](https://github.com/open-mmlab/mmsegmentation/blob/master/mmseg/models/decode_heads/uper_head.py)。

## 使用示例

UPerNet 是一个用于语义分割的通用框架。它可以与任意视觉骨干网络配合使用，例如：

```python
from transformers import SwinConfig, UperNetConfig, UperNetForSemanticSegmentation

backbone_config = SwinConfig(out_features=["stage1", "stage2", "stage3", "stage4"])

config = UperNetConfig(backbone_config=backbone_config)
model = UperNetForSemanticSegmentation(config)
```

若要使用其他视觉骨干网络，例如 [ConvNeXt](convnext)，只需使用相应的骨干网络实例化模型即可：

```python
from transformers import ConvNextConfig, UperNetConfig, UperNetForSemanticSegmentation

backbone_config = ConvNextConfig(out_features=["stage1", "stage2", "stage3", "stage4"])

config = UperNetConfig(backbone_config=backbone_config)
model = UperNetForSemanticSegmentation(config)
```

请注意，这将随机初始化模型的所有权重。

## 资源

一份来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，帮助你快速上手 UPerNet。

- UPerNet 的演示笔记本可在[此处](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/UPerNet)找到。
- [UperNetForSemanticSegmentation](/docs/transformers/main/zh/model_doc/upernet#transformers.UperNetForSemanticSegmentation) 受此 [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation.ipynb) 支持。
- 另请参阅：[语义分割任务指南](../tasks/semantic_segmentation)

如果您有兴趣提交资源以收录在此处，请随时发起 Pull Request，我们将对其进行审核！理想情况下，该资源应展示一些新内容，而不是重复现有资源。

## UperNetConfig[[transformers.UperNetConfig]]

#### transformers.UperNetConfig[[transformers.UperNetConfig]]

```python
transformers.UperNetConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, hidden_size: int = 512, initializer_range: float = 0.02, pool_scales: list[int] | tuple[int, ...] = (1, 2, 3, 6), use_auxiliary_head: bool = True, auxiliary_loss_weight: float = 0.4, auxiliary_in_channels: int | None = None, auxiliary_channels: int = 256, auxiliary_num_convs: int = 1, auxiliary_concat_input: bool = False, loss_ignore_index: int = 255)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/upernet/configuration_upernet.py#L25)

**参数：**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：骨干模型的配置。

hidden_size (`int`，*可选*，默认为 `512`)：隐藏表示的维度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

pool_scales (`tuple[int]`，*可选*，默认为 `[1, 2, 3, 6]`)：应用于最后一个特征图的池化金字塔模块（Pooling Pyramid Module）所使用的池化比例。

use_auxiliary_head (`bool`, *可选*, 默认为 `True`) : 是否在训练期间使用辅助头。

auxiliary_loss_weight (`float`, *可选*, 默认值为 0.4) : 辅助头交叉熵损失的权重。

auxiliary_in_channels (`int`，*可选*，默认为 256)：辅助头中的输入通道数。

auxiliary_channels (`int`，*可选*，默认为 256)：辅助头中使用的通道数。

auxiliary_num_convs (`int`，*可选*，默认为 1)：辅助头中使用的卷积层数。

auxiliary_concat_input (`bool`，*可选*，默认为 `False`)：是否将辅助头的输出与输入拼接，然后再送入分类层。

loss_ignore_index (`int`，*可选*，默认为 255)：损失函数忽略的索引。

这是用于存储 UpernetModel 配置的类。它根据指定的参数实例化 Upernet 模型，并定义模型架构。使用默认值实例化配置将得到与 [openmmlab/upernet-convnext-tiny](https://huggingface.co/openmmlab/upernet-convnext-tiny) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import UperNetConfig, UperNetForSemanticSegmentation

>>> # Initializing a configuration
>>> configuration = UperNetConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = UperNetForSemanticSegmentation(configuration)

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

## UperNetForSemanticSegmentation[[transformers.UperNetForSemanticSegmentation]]

#### transformers.UperNetForSemanticSegmentation[[transformers.UperNetForSemanticSegmentation]]

```python
transformers.UperNetForSemanticSegmentation(config: UperNetConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/upernet/modeling_upernet.py#L278)

**参数：**

config ([UperNetConfig](/docs/transformers/main/zh/model_doc/upernet#transformers.UperNetConfig))：包含模型所有参数的模型配置类。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

利用任意视觉骨干网络的 UperNet 框架，例如用于 ADE20k、CityScapes。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.UperNetForSemanticSegmentation.forward]]

```python
forward(pixel_values: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, labels: typing.Optional[torch.Tensor] = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/upernet/modeling_upernet.py#L293)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 获取像素值。有关详细信息，请参阅 [SegformerImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 处理图像）。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

labels (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*) : 用于计算损失的真实语义分割图。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `tuple(torch.Tensor)`

一个 [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[UperNetConfig](/docs/transformers/main/zh/model_doc/upernet#transformers.UperNetConfig)）和输入。

[UperNetForSemanticSegmentation](/docs/transformers/main/zh/model_doc/upernet#transformers.UperNetForSemanticSegmentation) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels, logits_height, logits_width)` 的 `torch.Tensor`）-- 每个像素的分类分数。

  

  返回的 logits 大小不一定与作为输入传入的 `pixel_values` 相同。这样设计是为了避免进行两次插值，从而在用户需要将 logits 调整为原始图像尺寸作为后处理时损失部分质量。您应始终检查 logits 的形状，并根据需要进行调整。

  
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, patch_size, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：
```python
>>> from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
>>> from PIL import Image
>>> from huggingface_hub import hf_hub_download

>>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny")
>>> model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny")

>>> filepath = hf_hub_download(
...     repo_id="hf-internal-testing/fixtures_ade20k", filename="ADE_val_00000001.jpg", repo_type="dataset"
... )
>>> image = Image.open(filepath).convert("RGB")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)

>>> logits = outputs.logits  # shape (batch_size, num_labels, height, width)
>>> list(logits.shape)
[1, 150, 512, 512]
```

