---
local: segformer
sections:
- local: overview
  title: Overview
- local: transformers.SegformerConfig
  title: SegformerConfig
- local: transformers.SegformerFeatureExtractor
  title: SegformerFeatureExtractor
- local: transformers.SegformerModel
  title: SegformerModel
- local: transformers.SegformerDecodeHead
  title: SegformerDecodeHead
- local: transformers.SegformerForImageClassification
  title: SegformerForImageClassification
- local: transformers.SegformerForSemanticSegmentation
  title: SegformerForSemanticSegmentation
title: SegFormer
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2021 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="segformer">SegFormer</h1>

<h2 id="overview">Overview</h2>

The SegFormer model was proposed in [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping
Luo. The model consists of a hierarchical Transformer encoder and a lightweight all-MLP decode head to achieve great
results on image segmentation benchmarks such as ADE20K and Cityscapes.

The abstract from the paper is the following:

*We present SegFormer, a simple, efficient yet powerful semantic segmentation framework which unifies Transformers with
lightweight multilayer perception (MLP) decoders. SegFormer has two appealing features: 1) SegFormer comprises a novel
hierarchically structured Transformer encoder which outputs multiscale features. It does not need positional encoding,
thereby avoiding the interpolation of positional codes which leads to decreased performance when the testing resolution
differs from training. 2) SegFormer avoids complex decoders. The proposed MLP decoder aggregates information from
different layers, and thus combining both local attention and global attention to render powerful representations. We
show that this simple and lightweight design is the key to efficient segmentation on Transformers. We scale our
approach up to obtain a series of models from SegFormer-B0 to SegFormer-B5, reaching significantly better performance
and efficiency than previous counterparts. For example, SegFormer-B4 achieves 50.3% mIoU on ADE20K with 64M parameters,
being 5x smaller and 2.2% better than the previous best method. Our best model, SegFormer-B5, achieves 84.0% mIoU on
Cityscapes validation set and shows excellent zero-shot robustness on Cityscapes-C.*

The figure below illustrates the architecture of SegFormer. Taken from the [original paper](https://arxiv.org/abs/2105.15203).

<img width="600" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/segformer_architecture.png"/>

This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/NVlabs/SegFormer).

Tips:

- SegFormer consists of a hierarchical Transformer encoder, and a lightweight all-MLP decode head.
  [SegformerModel](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerModel) is the hierarchical Transformer encoder (which in the paper is also referred to
  as Mix Transformer or MiT). [SegformerForSemanticSegmentation](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerForSemanticSegmentation) adds the all-MLP decode head on
  top to perform semantic segmentation of images. In addition, there's
  [SegformerForImageClassification](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerForImageClassification) which can be used to - you guessed it - classify images. The
  authors of SegFormer first pre-trained the Transformer encoder on ImageNet-1k to classify images. Next, they throw
  away the classification head, and replace it by the all-MLP decode head. Next, they fine-tune the model altogether on
  ADE20K, Cityscapes and COCO-stuff, which are important benchmarks for semantic segmentation. All checkpoints can be
  found on the [hub](https://huggingface.co/models?other=segformer).
- The quickest way to get started with SegFormer is by checking the [example notebooks](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/SegFormer) (which showcase both inference and
  fine-tuning on custom data).
- One can use [SegformerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor) to prepare images and corresponding segmentation maps
  for the model. Note that this feature extractor is fairly basic and does not include all data augmentations used in
  the original paper. The original preprocessing pipelines (for the ADE20k dataset for instance) can be found [here](https://github.com/NVlabs/SegFormer/blob/master/local_configs/_base_/datasets/ade20k_repeat.py). The most
  important preprocessing step is that images and segmentation maps are randomly cropped and padded to the same size,
  such as 512x512 or 640x640, after which they are normalized.
- One additional thing to keep in mind is that one can initialize [SegformerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor) with
  `reduce_labels` set to `True` or `False`. In some datasets (like ADE20k), the 0 index is used in the annotated
  segmentation maps for background. However, ADE20k doesn't include the "background" class in its 150 labels.
  Therefore, `reduce_labels` is used to reduce all labels by 1, and to make sure no loss is computed for the
  background class (i.e. it replaces 0 in the annotated maps by 255, which is the *ignore_index* of the loss function
  used by [SegformerForSemanticSegmentation](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerForSemanticSegmentation)). However, other datasets use the 0 index as
  background class and include this class as part of all labels. In that case, `reduce_labels` should be set to
  `False`, as loss should also be computed for the background class.
- As most models, SegFormer comes in different sizes, the details of which can be found in the table below.

| **Model variant** | **Depths**    | **Hidden sizes**    | **Decoder hidden size** | **Params (M)** | **ImageNet-1k Top 1** |
| :---------------: | ------------- | ------------------- | :---------------------: | :------------: | :-------------------: |
| MiT-b0            | [2, 2, 2, 2]  | [32, 64, 160, 256]  | 256                     | 3.7            | 70.5                  |
| MiT-b1            | [2, 2, 2, 2]  | [64, 128, 320, 512] | 256                     | 14.0           | 78.7                  |
| MiT-b2            | [3, 4, 6, 3]  | [64, 128, 320, 512] | 768                     | 25.4           | 81.6                  |
| MiT-b3            | [3, 4, 18, 3] | [64, 128, 320, 512] | 768                     | 45.2           | 83.1                  |
| MiT-b4            | [3, 8, 27, 3] | [64, 128, 320, 512] | 768                     | 62.6           | 83.6                  |
| MiT-b5            | [3, 6, 40, 3] | [64, 128, 320, 512] | 768                     | 82.0           | 83.8                  |

<h2 id="transformers.SegformerConfig">SegformerConfig</h2>

<div class="docstring">

<docstring><name>class transformers.SegformerConfig</name><anchor>transformers.SegformerConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/configuration_segformer.py#L29</source><parameters>[{"name": "image_size", "val": " = 224"}, {"name": "num_channels", "val": " = 3"}, {"name": "num_encoder_blocks", "val": " = 4"}, {"name": "depths", "val": " = [2, 2, 2, 2]"}, {"name": "sr_ratios", "val": " = [8, 4, 2, 1]"}, {"name": "hidden_sizes", "val": " = [32, 64, 160, 256]"}, {"name": "downsampling_rates", "val": " = [1, 4, 8, 16]"}, {"name": "patch_sizes", "val": " = [7, 3, 3, 3]"}, {"name": "strides", "val": " = [4, 2, 2, 2]"}, {"name": "num_attention_heads", "val": " = [1, 2, 5, 8]"}, {"name": "mlp_ratios", "val": " = [4, 4, 4, 4]"}, {"name": "hidden_act", "val": " = 'gelu'"}, {"name": "hidden_dropout_prob", "val": " = 0.0"}, {"name": "attention_probs_dropout_prob", "val": " = 0.0"}, {"name": "classifier_dropout_prob", "val": " = 0.1"}, {"name": "initializer_range", "val": " = 0.02"}, {"name": "drop_path_rate", "val": " = 0.1"}, {"name": "layer_norm_eps", "val": " = 1e-06"}, {"name": "decoder_hidden_size", "val": " = 256"}, {"name": "is_encoder_decoder", "val": " = False"}, {"name": "reshape_last_stage", "val": " = True"}, {"name": "semantic_loss_ignore_index", "val": " = 255"}, {"name": "legacy_output", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **image_size** (`int`, *optional*, defaults to 512) --
  The size (resolution) of each image.
- **num_channels** (`int`, *optional*, defaults to 3) --
  The number of input channels.
- **num_encoder_blocks** (`int`, *optional*, defaults to 4) --
  The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
- **depths** (`List[int]`, *optional*, defaults to [2, 2, 2, 2]) --
  The number of layers in each encoder block.
- **sr_ratios** (`List[int]`, *optional*, defaults to [8, 4, 2, 1]) --
  Sequence reduction ratios in each encoder block.
- **hidden_sizes** (`List[int]`, *optional*, defaults to [32, 64, 160, 256]) --
  Dimension of each of the encoder blocks.
- **downsampling_rates** (`List[int]`, *optional*, defaults to [1, 4, 8, 16]) --
  Downsample rate of the image resolution compared to the original image size before each encoder block.
- **patch_sizes** (`List[int]`, *optional*, defaults to [7, 3, 3, 3]) --
  Patch size before each encoder block.
- **strides** (`List[int]`, *optional*, defaults to [4, 2, 2, 2]) --
  Stride before each encoder block.
- **num_attention_heads** (`List[int]`, *optional*, defaults to [1, 2, 4, 8]) --
  Number of attention heads for each attention layer in each block of the Transformer encoder.
- **mlp_ratios** (`List[int]`, *optional*, defaults to [4, 4, 4, 4]) --
  Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
  encoder blocks.
- **hidden_act** (`str` or `function`, *optional*, defaults to `"gelu"`) --
  The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  `"relu"`, `"selu"` and `"gelu_new"` are supported.
- **hidden_dropout_prob** (`float`, *optional*, defaults to 0.0) --
  The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
- **attention_probs_dropout_prob** (`float`, *optional*, defaults to 0.0) --
  The dropout ratio for the attention probabilities.
- **classifier_dropout_prob** (`float`, *optional*, defaults to 0.1) --
  The dropout probability before the classification head.
- **initializer_range** (`float`, *optional*, defaults to 0.02) --
  The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- **drop_path_rate** (`float`, *optional*, defaults to 0.1) --
  The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
- **layer_norm_eps** (`float`, *optional*, defaults to 1e-6) --
  The epsilon used by the layer normalization layers.
- **decoder_hidden_size** (`int`, *optional*, defaults to 256) --
  The dimension of the all-MLP decode head.
- **reshape_last_stage** (`bool`, *optional*, defaults to `True`) --
  Whether to reshape the features of the last stage back to `(batch_size, num_channels, height, width)`. Only
  required for the semantic segmentation model.
- **semantic_loss_ignore_index** (`int`, *optional*, defaults to 255) --
  The index that is ignored by the loss function of the semantic segmentation model.
- **legacy_output** (`bool`, *optional*, defaults to `False`) --
  Whether to return the legacy outputs or not (with logits of shape `height / 4 , width / 4`)

  This argument is only present for backward compatibility reasons and will be removed in v5 of Transformers.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [SegformerModel](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerModel). It is used to instantiate an
SegFormer model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the SegFormer
[nvidia/segformer-b0-finetuned-ade-512-512](https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512)
architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.



Example:

```python
>>> from transformers import SegformerModel, SegformerConfig

>>> # Initializing a SegFormer nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> configuration = SegformerConfig()

>>> # Initializing a model from the nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> model = SegformerModel(configuration)

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

</div>

<h2 id="transformers.SegformerFeatureExtractor">SegformerFeatureExtractor</h2>

<div class="docstring">

<docstring><name>class transformers.SegformerFeatureExtractor</name><anchor>transformers.SegformerFeatureExtractor</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/feature_extraction_segformer.py#L37</source><parameters>[{"name": "do_resize", "val": " = True"}, {"name": "size", "val": " = 512"}, {"name": "resample", "val": " = 2"}, {"name": "do_normalize", "val": " = True"}, {"name": "image_mean", "val": " = None"}, {"name": "image_std", "val": " = None"}, {"name": "reduce_labels", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **do_resize** (`bool`, *optional*, defaults to `True`) --
  Whether to resize the input based on a certain `size`.
- **size** (`int` or `Tuple(int)`, *optional*, defaults to 512) --
  Resize the input to the given size. If a tuple is provided, it should be (width, height). If only an
  integer is provided, then the input will be resized to (size, size). Only has an effect if `do_resize` is
  set to `True`.
- **resample** (`int`, *optional*, defaults to `PIL.Image.BILINEAR`) --
  An optional resampling filter. This can be one of `PIL.Image.NEAREST`, `PIL.Image.BOX`,
  `PIL.Image.BILINEAR`, `PIL.Image.HAMMING`, `PIL.Image.BICUBIC` or `PIL.Image.LANCZOS`. Only has an effect
  if `do_resize` is set to `True`.
- **do_normalize** (`bool`, *optional*, defaults to `True`) --
  Whether or not to normalize the input with mean and standard deviation.
- **image_mean** (`int`, *optional*, defaults to `[0.485, 0.456, 0.406]`) --
  The sequence of means for each channel, to be used when normalizing images. Defaults to the ImageNet mean.
- **image_std** (`int`, *optional*, defaults to `[0.229, 0.224, 0.225]`) --
  The sequence of standard deviations for each channel, to be used when normalizing images. Defaults to the
  ImageNet std.
- **reduce_labels** (`bool`, *optional*, defaults to `False`) --
  Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is
  used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The
  background label will be replaced by 255.</paramsdesc><paramgroups>0</paramgroups></docstring>

Constructs a SegFormer feature extractor.

This feature extractor inherits from [FeatureExtractionMixin](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.FeatureExtractionMixin) which contains most of the main methods. Users
should refer to this superclass for more information regarding those methods.





<div class="docstring">
<docstring><name>\_\_call\_\_</name><anchor>transformers.SegformerFeatureExtractor.__call__</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/feature_extraction_segformer.py#L90</source><parameters>[{"name": "images", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]]"}, {"name": "segmentation_maps", "val": ": typing.Union[PIL.Image.Image, numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] = None"}, {"name": "return_tensors", "val": ": typing.Union[str, transformers.file_utils.TensorType, NoneType] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **images** (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`) --
  The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is
  the number of channels, H and W are image height and width.

- **segmentation_maps** (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*) --
  Optionally, the corresponding semantic segmentation maps with the pixel-wise annotations.

- **return_tensors** (`str` or [TensorType](/docs/transformers/pr_15592/en/internal/file_utils#transformers.TensorType), *optional*, defaults to `'np'`) --
  If set, will return tensors of a particular framework. Acceptable values are:

  - `'tf'`: Return TensorFlow `tf.constant` objects.
  - `'pt'`: Return PyTorch `torch.Tensor` objects.
  - `'np'`: Return NumPy `np.ndarray` objects.
  - `'jax'`: Return JAX `jnp.ndarray` objects.</paramsdesc><paramgroups>0</paramgroups><rettype>[BatchFeature](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.BatchFeature)</rettype><retdesc>A [BatchFeature](/docs/transformers/pr_15592/en/main_classes/feature_extractor#transformers.BatchFeature) with the following fields:

- **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
  width).
- **labels** -- Optional labels to be fed to a model (when `segmentation_maps` are provided)</retdesc></docstring>

Main method to prepare for the model one or several image(s) and optional corresponding segmentation maps.

<Tip warning=&amp;lcub;true}>

NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass
PIL images.

</Tip>








</div></div>

<h2 id="transformers.SegformerModel">SegformerModel</h2>

<div class="docstring">

<docstring><name>class transformers.SegformerModel</name><anchor>transformers.SegformerModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L477</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) -- Model configuration class with all the parameters of the model.
  Initializing with a config file does not load the weights associated with the model, only the
  configuration. Check out the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.SegformerModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L496</source><parameters>[{"name": "pixel_values", "val": ""}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) --
  Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
  [SegformerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor). See [SegformerFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor.__call__) for details.

- **output_attentions** (`bool`, *optional*) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  tensors for more detail.
- **output_hidden_states** (`bool`, *optional*) --
  Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  more detail.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.BaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.BaseModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) and inputs.

- **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the initial embedding outputs.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.</retdesc></docstring>
The [SegformerModel](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>








Example:

```python
>>> from transformers import SegformerFeatureExtractor, SegformerModel
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/mit-b0")
>>> model = SegformerModel.from_pretrained("nvidia/mit-b0")

>>> inputs = feature_extractor(image, return_tensors="pt")

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 256, 256]
```


</div></div>

<h2 id="transformers.SegformerDecodeHead">SegformerDecodeHead</h2>

<div class="docstring">

<div class="docstring"></div></div>

<h2 id="transformers.SegformerForImageClassification">SegformerForImageClassification</h2>

<div class="docstring">

<docstring><name>class transformers.SegformerForImageClassification</name><anchor>transformers.SegformerForImageClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L537</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) -- Model configuration class with all the parameters of the model.
  Initializing with a config file does not load the weights associated with the model, only the
  configuration. Check out the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden
states) e.g. for ImageNet.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.SegformerForImageClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L550</source><parameters>[{"name": "pixel_values", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) --
  Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
  [SegformerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor). See [SegformerFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor.__call__) for details.

- **output_attentions** (`bool`, *optional*) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  tensors for more detail.
- **output_hidden_states** (`bool`, *optional*) --
  Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  more detail.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  `config.num_labels > 1` a classification loss is computed (Cross-Entropy).</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Classification (or regression if config.num_labels==1) loss.
- **logits** (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) -- Classification (or regression if config.num_labels==1) scores (before SoftMax).
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, sequence_length, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the initial embedding outputs.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.</retdesc></docstring>
The [SegformerForImageClassification](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerForImageClassification) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>








Example:

```python
>>> from transformers import SegformerFeatureExtractor, SegformerForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/mit-b0")
>>> model = SegformerForImageClassification.from_pretrained("nvidia/mit-b0")

>>> inputs = feature_extractor(image, return_tensors="pt")

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

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
'tabby, tabby cat'
```


</div></div>

<h2 id="transformers.SegformerForSemanticSegmentation">SegformerForSemanticSegmentation</h2>

<div class="docstring">

<docstring><name>class transformers.SegformerForSemanticSegmentation</name><anchor>transformers.SegformerForSemanticSegmentation</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L682</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) -- Model configuration class with all the parameters of the model.
  Initializing with a config file does not load the weights associated with the model, only the
  configuration. Check out the [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.SegformerForSemanticSegmentation.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/segformer/modeling_segformer.py#L691</source><parameters>[{"name": "pixel_values", "val": ""}, {"name": "labels", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "legacy_output", "val": " = None"}]</parameters><paramsdesc>- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) --
  Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
  [SegformerFeatureExtractor](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor). See [SegformerFeatureExtractor.__call__()](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerFeatureExtractor.__call__) for details.

- **output_attentions** (`bool`, *optional*) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  tensors for more detail.
- **output_hidden_states** (`bool`, *optional*) --
  Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  more detail.
- **return_dict** (`bool`, *optional*) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.

- **labels** (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*) --
  Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
  config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
- **legacy_output** (`bool`, *optional*) --
  Whether to return the legacy outputs or not (with logits of shape `height / 4 , width / 4`). Will default
  to `self.config.legacy_output`.

  This argument is only present for backward compatibility reasons and will be removed in v5 of Transformers.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.modeling_outputs.SemanticSegmentationModelOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>A `transformers.modeling_outputs.SemanticSegmentationModelOutput`or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([SegformerConfig](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Classification (or regression if config.num_labels==1) loss.
- **logits** (`torch.FloatTensor` of shape `(batch_size, config.num_labels, height, width)`) -- Classification scores for each pixel.
- **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  shape `(batch_size, patch_size, hidden_size)`.

  Hidden-states of the model at the output of each layer plus the initial embedding outputs.
- **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size,
  sequence_length)`.

  Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  heads.</retdesc></docstring>
The [SegformerForSemanticSegmentation](/docs/transformers/pr_15592/en/model_doc/segformer#transformers.SegformerForSemanticSegmentation) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>








Examples:

```python
>>> from transformers import SegformerFeatureExtractor, SegformerForSemanticSegmentation
>>> from PIL import Image
>>> import requests

>>> feature_extractor = SegformerFeatureExtractor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
>>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")

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

>>> inputs = feature_extractor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits  # shape (batch_size, num_labels, height, width)
```

</div></div>
