Back to paper library
arXiv 2021NeurIPS 2021SegmentationPaper notes

SegFormer

Is an MLP Enough?

Original paper

SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers

Paper authors

Enze Xie · Wenhai Wang · Zhiding Yu · Anima Anandkumar · Jose M. Alvarez · Ping Luo

Publication
NeurIPS 2021Conference
First submitted to arXiv
arXiv:2105.15203
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{segmentationsegformer2021,
  title = {{SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers}},
  author = {Enze Xie and Wenhai Wang and Zhiding Yu and Anima Anandkumar and Jose M. Alvarez and Ping Luo},
  year = {2021},
  eprint = {2105.15203},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2105.15203}
}
On this page

After ViT showed in 2020 that Transformers could do image classification, people quickly wanted to move them over to segmentation. At the end of 2020, SETR took ViT-Large directly as its backbone, attached a few convolutional decoders, and reached 50.2% mIoU on ADE20K.

The results were good, but the model was hard to use. SETR has 318 million parameters and runs at less than one image per second on Cityscapes; ViT outputs only one resolution, and its positional encoding is tied to the image size used in training.

SegFormer, from Enze Xie and Ping Luo of the University of Hong Kong together with a team at NVIDIA, redesigns the encoder and the decoder together. Its largest model reaches 51.8% on ADE20K with just over a quarter of SETR's parameters, and its smallest model has fewer than 4 million parameters and runs in real time.

Defining the Problem

The CNN segmentation models in the previous notes were mostly a backbone plus a heavy decoder. DeepLab has ASPP and PSPNet has pyramid pooling, both there to make up for the CNN's receptive field not being large enough.

ViT's receptive field is not the problem, since self-attention sees the whole image from the very start. It has other weaknesses.

First, ViT cuts the image into 16×1616\times16 patches and has only one resolution from start to finish. Segmentation needs high-resolution detail as well as low-resolution semantics, and ViT provides only the latter.

Second, the cost of self-attention grows with the square of the number of tokens. Segmentation inputs are often 1024×20481024\times2048, and cut into small patches the token count explodes.

Third, ViT's positional encoding has a fixed length. When the test image size differs from training, the positional encoding has to be interpolated, and accuracy drops. Segmentation, of all tasks, often runs inference at a different resolution, for example feeding Cityscapes' full 1024×20481024\times2048 images straight in.

PVT, Swin, Twins and other hierarchical Transformers solved the first two problems; like CNNs, they output multi-scale features, and they keep the computation down. But the authors observed that these works changed almost nothing but the encoder, copying the decoder from CNN-era designs. Transformer features differ from CNN features, so shouldn't the decoder differ too?

Solving the Problem

Original Figure 2: the SegFormer framework. The left half is the encoder; the image goes through Overlap Patch Embeddings and then four Transformer Blocks in turn, outputting features at four resolutions, H/4×W/4×C1, H/8×W/8×C2, H/16×W/16×C3 and H/32×W/32×C4; the zoomed view below shows each Block repeating Efficient Self-Attn and Mix-FFN N times, followed by Overlap Patch Merging. The right half is the decoder; each of the four sets of features goes through an MLP and is upsampled to H/4×W/4, they are concatenated into 4C channels, and another MLP outputs the H/4×W/4×N_cls segmentation result.
Original Figure 2, Xie et al., from PDF page 3, arXiv license, scholarly quotation.

SegFormer has just two parts. On the left is a hierarchical Transformer encoder, which the authors call the Mix Transformer (MiT), in six sizes from B0 to B5; on the right is a decoder made only of MLPs.

Let's walk through it with the 512×512512\times512 input used for ADE20K training and the medium-sized MiT-B2. B2's four stages have 64, 128, 320 and 512 channels.

Overlapping Patches

The first step cuts the image into patches. ViT uses non-overlapping 16×1616\times16 patches; SegFormer uses a 7×77\times7 convolution with stride 4 and padding 3, so neighboring patches overlap.

The 512×512512\times512 image becomes 128×128128\times128 tokens of 64 dimensions each, at 1/41/4 of the original resolution. The next three stages each halve it again with a 3×33\times3, stride-2 convolution, giving 64×64×12864\times64\times128, 32×32×32032\times32\times320 and 16×16×51216\times16\times512 in turn.

The reason for the overlap is to keep continuity around patch borders. A non-overlapping cut can split an object's edge right between two patches, and the information on either side is separated from the very start.

Shrinking K and V

The first stage has 128×128=16,384128\times128=16{,}384 tokens. Standard self-attention computes a 16384×1638416384\times16384 matrix, about 270 million entries, once per layer and per head.

SegFormer keeps PVT's sequence reduction. The queries stay at the original 16,384, while keys and values are first shrunk spatially before the computation. The paper writes this as merging every RR neighboring tokens into one:

K^=Reshape(NR, C⋅R)(K)K=Linear(C⋅R, C)(K^)\begin{aligned} \hat{K} &= \text{Reshape}\left(\frac{N}{R},\ C\cdot R\right)(K) \\ K &= \text{Linear}(C\cdot R,\ C)(\hat{K}) \end{aligned}

The first stage uses R=64R=64, which amounts to shrinking each side 8× in space. The official implementation uses a convolution whose kernel size and stride both equal 8, with the same effect. The 128×128128\times128 features shrink to 16×16=25616\times16=256 tokens for K and V, and the attention matrix becomes 16384×25616384\times256, 64 times smaller.

The four stages use reduction ratios of 64, 16, 4 and 1 (8, 4, 2 and 1 per side). Working through our example:

StageTokensPer sideK, V tokens
1128×128=16,384128\times128=16{,}3848256
264×64=4,09664\times64=4{,}0964256
332×32=1,02432\times32=1{,}0242256
416×16=25616\times16=2561256

With a 512×512512\times512 input, every token in every stage attends over 256 keys and values. The reduction ratios are chosen so that K and V have the same length in all four stages.

No Positional Encoding

ViT needs positional encoding because self-attention on its own doesn't know where the tokens are. SegFormer removes it entirely and instead puts a 3×33\times3 convolution inside the feed-forward network:

h=GELU(Conv3×3(MLP(xin)))xout=MLP(h)+xin\begin{aligned} \mathbf{h} &= \text{GELU}\big(\text{Conv}_{3\times3}(\text{MLP}(\mathbf{x}_{\text{in}}))\big) \\ \mathbf{x}_{\text{out}} &= \text{MLP}(\mathbf{h}) + \mathbf{x}_{\text{in}} \end{aligned}

This is called Mix-FFN. The convolution is depthwise and has very few parameters.

Without positional encoding, how does the model know about position? The authors cite Islam et al., who showed that when a convolution zero-pads at the borders, it leaks "how far from the border" to the network, so a single 3×33\times3 convolution is enough to supply the position information a Transformer needs. CPVT also generates position information with convolutions, but what it produces is still a positional encoding added back to the tokens; SegFormer drops that encoding altogether and puts the convolution straight into the FFN.

The benefit is that the resolution can change freely. With no fixed-length positional encoding, there's nothing to interpolate.

A Decoder in Four Steps

The encoder outputs four sets of features, at resolutions from 1/41/4 to 1/321/32. The decoder does four things:

  1. Each set of features goes through its own linear layer, which brings the channel count to a common CC.
  2. Everything is upsampled to 1/41/4, which here is 128×128128\times128.
  3. The results are concatenated into 4C4C channels, and one linear layer fuses them back to CC.
  4. A final linear layer outputs a score for each class; ADE20K has 150.

As equations,

F^i=Linear(Ci,C)(Fi)F^i=Upsample(H4×W4)(F^i)F=Linear(4C,C)(Concat(F^i))M=Linear(C,Ncls)(F)\begin{aligned} \hat{F}_i &= \text{Linear}(C_i, C)(F_i) \\ \hat{F}_i &= \text{Upsample}\left(\tfrac{H}{4}\times\tfrac{W}{4}\right)(\hat{F}_i) \\ F &= \text{Linear}(4C, C)(\text{Concat}(\hat{F}_i)) \\ M &= \text{Linear}(C, N_{cls})(F) \end{aligned}

No ASPP, no pyramid pooling, no 3×33\times3 convolutions. From B2 up, CC is 768 and the decoder has 3.3 million parameters in total; for B0 and B1, CC is 256, and B0's decoder has only 0.4 million parameters. In the official implementation the fusion layer is a 1×11\times1 convolution plus BatchNorm, equivalent to a linear layer.

Why is such a simple decoder enough? The authors explain it with the effective receptive field (ERF).

Original Figure 3: the top row is DeepLabv3+ and the bottom row SegFormer; from left to right are the effective receptive fields of the four stages and of the decoder head, where a brighter background means more influence on the center pixel; at the far right are zoomed views of the central regions of stage 4 (red box) and the decoder head (blue box). DeepLabv3+'s bright spot is still concentrated in a small central patch at stage 4, and its decoder head shows radial dots; SegFormer has brightness across the whole image from stage 3 on, and its decoder head shows a distinct central bright spot on top of the global background.
Original Figure 3, Xie et al., from PDF page 5, arXiv license, scholarly quotation.

This figure is averaged over 100 Cityscapes images. Look at DeepLabv3+ in the top row. Even at the deepest stage, stage 4, its effective receptive field is still a small central patch, which is why it needs ASPP in the decoder head to make up the receptive field. The radial bright dots in the decoder head panel look like the traces of ASPP's several different sampling intervals.

SegFormer in the bottom row is different. The attention in the first two stages is very local and looks like convolution; by stage 4, the whole image is lit up. In the zoomed view at the far right, the decoder head has a more concentrated central bright spot than stage 4 does.

The authors' reading is that SegFormer's low-level features are naturally local and its high-level features naturally global, so the decoder only has to add the levels together to get both local detail and global context. A CNN's high-level receptive field is small to begin with, so the same decoder after a CNN falls short, which the experiments will confirm.

Discussion

Model Sizes

The experiments are trained with mmsegmentation on 8 V100s, with AdamW and a learning rate of 6×10−56\times10^{-5}, for 160K iterations on ADE20K and Cityscapes, and without common tricks such as OHEM, auxiliary losses or class balancing. Table 1a of the paper lists six sizes:

EncoderParams (enc.+dec.)ADE20K mIoUCityscapes mIoUCOCO-Stuff mIoU
MiT-B03.4M+0.4M37.476.235.6
MiT-B113.1M+0.6M42.278.540.2
MiT-B224.2M+3.3M46.581.044.6
MiT-B344.0M+3.3M49.481.745.5
MiT-B460.8M+3.3M50.382.346.5
MiT-B581.4M+3.3M51.082.446.7

All numbers are single-scale testing. As the encoder grows, all three datasets improve steadily; in B5 the decoder makes up only about 4% of the total parameters.

The decoder's channel count CC was tested too (Table 1b of the paper). On ADE20K, raising CC from 256 to 768 takes mIoU from 44.9 to 45.4, after which it levels off; C=2048C=2048 gives 45.6, while the computation jumps from 25.7 to 304.4 GFLOPs.

Is Positional Encoding Really Unnecessary?

Table 1c of the paper compares two ways of running inference on Cityscapes. One uses a 768×768768\times768 sliding window; the other feeds the whole 1024×20481024\times2048 image straight in.

Encoder768×768768\times768 window1024×20481024\times2048 whole
Positional encoding77.374.0
Mix-FFN80.579.8

The positional-encoding version loses 3.3 points when switched to the whole image; Mix-FFN loses only 0.7. And with the same sliding window, Mix-FFN is already 3.2 points higher on its own.

Does the Decoder Really Only Work with a Transformer?

Table 1d of the paper attaches the same MLP decoder to different encoders and compares them on ADE20K:

EncoderGFLOPsmIoU
ResNet-50 (stage 1–4)69.234.7
ResNet-101 (stage 1–4)88.738.7
ResNeXt-101 (stage 1–4)127.539.8
MiT-B2 (stage 4 only)22.343.1
MiT-B2 (stage 1–4)62.445.4

Behind a CNN, even the best encoder, ResNeXt-101, reaches only 39.8, at twice the computation of MiT-B2. This echoes the ERF analysis; the CNN's receptive field isn't large enough, and an MLP alone can't make up for it. MiT-B2 using only the last stage gets 43.1, and using all four stages gets 45.4, so the low-level local features really do help.

Against Other Methods

Table 2 of the paper is split into real-time and non-real-time groups. In the real-time group, SegFormer-B0 reaches 37.4% on ADE20K with 3.8M parameters and 8.4 GFLOPs, 3.4 points above DeepLabV3+ with a MobileNetV2 backbone, using only a quarter of its parameters.

The non-real-time group reports multi-scale test results on ADE20K. SETR gets 50.2% with 318.3M parameters, SegFormer-B4 51.1% with 64.1M, and B5 51.8% with 84.7M. On the Cityscapes validation set, B5 gets 84.0% and SETR 82.2%, with B5 running at 2.5 images per second and SETR at 0.5.

The introduction says B0 runs on Cityscapes "at 48 images per second with 71.9%, faster than ICNet and 4.2 points more accurate." Those numbers correspond to the setting in Table 2 that resizes the short side to 512, which is 512×1024512\times1024, only a quarter of the original image's pixels. The same B0 with a short side of 1024 gets 76.2% at 15.2 images per second. ICNet's 30.3 FPS, meanwhile, comes from ICNet's own paper, and the hardware may not be the same either. As with BiSeNet in the previous note, real-time segmentation FPS always has to be read together with the resolution and the hardware.

On the Cityscapes test set (Table 3 of the paper), B5 pretrained only on ImageNet-1K gets 82.2%, above SETR (81.6%), which used ImageNet-22K plus coarse annotations; adding Mapillary pretraining brings it to 83.1%.

Robustness

The last set of experiments is on Cityscapes-C. This is the Cityscapes validation set with 16 kinds of synthetic corruption, covering noise, blur, weather and digital distortion, used to test degradations the model has never seen.

A few of the columns (Table 5 of the paper, mIoU):

MethodCleanGauss noiseShot noiseSnowFog
DeepLabv3+ (ResNet-101)77.113.216.311.955.1
PSPNet78.811.015.48.434.4
SegFormer-B582.457.852.340.778.5

On clean images SegFormer is only 3.6 points above PSPNet, but with Gaussian noise added, PSPNet is left with 11.0 while SegFormer still has 57.8. The authors read this as the robustness of the Transformer encoder. The other methods' numbers in the table, however, all come from Kamann and Rother's benchmark paper, while SegFormer's were run by the authors themselves; the experiment also doesn't separate how much comes from "the Transformer architecture" and how much from "a bigger model and a better training setup."

At the end, the paper admits one limitation. B0 is smaller than any known CNN model, but whether it can fit on an edge chip with only 100k of memory, the authors don't know either.

Conclusion

The encoder handles multiple scales and context, and the decoder just adds the four levels of features together; that is how SegFormer divides the work. Overlapping patches, attention with reduced K/V and Mix-FFN let the encoder do without positional encoding, so even inference on whole 1024×20481024\times2048 images loses only 0.7 points; from B0 to B5, the same design scales from a real-time model all the way up to 51.8% on ADE20K.

If you want to use it right away, Hugging Face's transformers has SegformerForSemanticSegmentation, and weights for B0 through B5 are all available to download.

Just don't take that MLP decoder off and bolt it onto a ResNet. The paper tried; ResNeXt-101 with it gets only 39.8, more than 5 points below MiT-B2, and the decoder is only enough when it sits behind a Transformer encoder.