Back to paper library
arXiv 2021NeurIPS 2021SegmentationPaper notes

MaskFormer

Birds of a Feather

Original paper

Per-Pixel Classification is Not All You Need for Semantic Segmentation

Paper authors

Bowen Cheng · Alexander G. Schwing · Alexander Kirillov

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

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

@misc{segmentationmaskformer2021,
  title = {{Per-Pixel Classification is Not All You Need for Semantic Segmentation}},
  author = {Bowen Cheng and Alexander G. Schwing and Alexander Kirillov},
  year = {2021},
  eprint = {2107.06278},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2107.06278}
}
On this page

Ever since FCN, semantic segmentation has been treated as per-pixel classification. Each pixel outputs a probability distribution over KK classes, you compute the cross-entropy, done. DeepLab, PSPNet and SegFormer swapped in plenty of backbones and decoders, but nobody touched the way the question itself was posed.

Instance segmentation took a different road. Mask R-CNN predicts one mask for each object and then gives that mask a class; when DETR does panoptic segmentation, it also maps one query to one region and one class.

Bowen Cheng and Alexander Schwing of UIUC and Alexander Kirillov of FAIR borrowed the sentence pattern of "Attention Is All You Need" to name this paper, and argued the other way round, that semantic segmentation can also be done as mask classification, and that one model with one set of losses can solve semantic and panoptic segmentation together.

Defining the Problem

Original Figure 1: on the left is per-pixel classification, where every pixel of the image outputs scores for K classes and the same classification loss is applied at each position; on the right is mask classification, where the model outputs N predictions, each a binary mask (for example the shape of a building or of the sky) plus a label over K+1 classes, the extra class being "no object" ∅; each prediction is supervised by both a per-pixel binary mask loss and a classification loss on the whole mask.
Original Figure 1, Cheng et al., from PDF page 2, arXiv license, scholarly quotation.

On the left is the per-pixel classification we all know; on the right is mask classification. Mask classification splits segmentation into two jobs, first cutting the image into NN pieces, each represented by a binary mask, and then giving each piece, as a whole, one class.

Per-pixel classification has a built-in limit, which is that the number of outputs is fixed. An image always yields score maps for KK classes. It can tell you which pixels are people, but it has no way to return an answer whose size varies, like "three people." So instance segmentation can only be done with mask classification.

The reverse has no such limit. Mask classification allows several masks to share a class, and allows only some of the classes to be output, so it can do instance segmentation as well as semantic segmentation. The authors also point out that before FCN, the best semantic segmentation methods on PASCAL VOC, such as O2P and SDS, already worked by generating candidate regions first and then classifying the regions.

So this paper sets out to answer two questions. Can a single mask classification model handle both semantic- and instance-level segmentation? And on semantic segmentation, can it beat per-pixel classification?

How Mask Classification Is Trained

Training per-pixel classification is straightforward; each pixel has one correct class, and you just compute cross-entropy. The output of mask classification is a set z={(pi,mi)}i=1Nz=\{(p_i, m_i)\}_{i=1}^{N}, where pip_i is a probability over K+1K+1 classes (with one extra, "no object" ∅\varnothing) and mim_i is an H×WH\times W mask. The annotation is a set too, with one class and one mask for each ground-truth region.

The two sets have to be matched first, so we know which prediction is responsible for which annotation.

The simplest matching sets N=KN=K, so the ii-th prediction is always responsible for the ii-th class, and if that class doesn't appear in the image, it is matched to ∅\varnothing. Mask classification done this way is little more than per-pixel classification written differently.

The other option is DETR's bipartite matching, which uses the Hungarian algorithm to find the one-to-one matching with the lowest total cost. DETR's matching cost uses boxes; MaskFormer uses the class probabilities and the masks directly, and the cost of pairing prediction ii with annotation jj is −pi(cjgt)+Lmask(mi,mjgt)-p_i(c_j^{gt}) + \mathcal{L}_{mask}(m_i, m_j^{gt}).

Once matched, the loss is

Lmask-cls=∑j=1Nℓjℓj=−log⁡pσ(j)(cjgt)+1cjgt≠∅ Lmask(mσ(j),mjgt)\begin{aligned} \mathcal{L}_{mask\text{-}cls} &= \sum_{j=1}^{N} \ell_j \\ \ell_j &= -\log p_{\sigma(j)}(c_j^{gt}) \\ &\quad + \mathbb{1}_{c_j^{gt}\neq\varnothing}\,\mathcal{L}_{mask}\big(m_{\sigma(j)}, m_j^{gt}\big) \end{aligned}

σ\sigma is the matching. Every prediction has to get its class right; a prediction matched to a real region also has to make its mask overlap the annotation. Lmask\mathcal{L}_{mask} follows DETR and is a weighted sum of focal loss and dice loss.

Solving the Problem

Original Figure 2: MaskFormer overview. Bottom left is the pixel-level module, where the backbone extracts image features F and the pixel decoder upsamples them into per-pixel embeddings E_pixel (C_E×H×W); top left is the Transformer module, where N queries pass through a Transformer decoder that attends to the image features and outputs N segment embeddings Q; on the right is the segmentation module, where Q passes through a classifier to give N×(K+1) class predictions and through an MLP to give N mask embeddings E_mask (C_E×N), and the dot product of the mask embeddings with the per-pixel embeddings gives N×H×W masks; the dashed box on the far right is a step used only for semantic segmentation inference, which drops ∅ and multiplies the class predictions with the masks to give a K×H×W semantic segmentation.
Original Figure 2, Cheng et al., from PDF page 4, arXiv license, scholarly quotation.

MaskFormer has three modules. There are a fair number of components in this figure, so we'll walk through it with the ADE20K setup: a 512×512512\times512 input, a ResNet-50 backbone, 150 classes and 100 queries.

Pixel-Level Module

The backbone outputs a stride-32 feature map F\mathcal{F}; a 512×512512\times512 image gives 16×1616\times16 positions, and the last layer of ResNet-50 has 2048 channels.

The pixel decoder enlarges it step by step to stride 4. The authors use a lightweight FPN. Each step upsamples the lower-resolution features by 2×, adds the backbone features of the same resolution, and fuses them with a 3×33\times3 convolution, going all the way from stride 32 down to stride 4; a final 1×11\times1 convolution outputs the per-pixel embeddings Epixel\mathcal{E}_{pixel}.

In our example, Epixel\mathcal{E}_{pixel} is 256×128×128256\times128\times128, a 256-dimensional vector at every pixel position.

A per-pixel classification model would attach a classifier right after this step and output a 150×128×128150\times128\times128 score map. MaskFormer stops at the embeddings and doesn't classify. That's why the authors say any per-pixel classification segmentation model can serve as the pixel-level module; swap out the final classification head and it becomes mask classification.

Transformer Module

This part is the same as DETR's decoder. The 100 learnable queries pass through 6 layers of a standard Transformer decoder, and each layer does cross-attention over the image features F\mathcal{F} (16×1616\times16 positions). The output QQ is 100 segment embeddings of 256 dimensions, each standing for one possible region.

Note that the queries look at the low-resolution stride-32 features, not at Epixel\mathcal{E}_{pixel}. The queries only need to know "what is in this image"; the details are left to the pixel decoder.

Segmentation Module

Each segment embedding splits into two branches:

  • Class: a linear layer plus softmax outputs probabilities over 151 classes (150 classes plus ∅\varnothing), giving 100×151100\times151.
  • Mask: an MLP with two hidden layers turns it into a 256-dimensional mask embedding Emask\mathcal{E}_{mask}, giving 256×100256\times100.

The masks come from a dot product. Write the ii-th mask embedding as ei=Emask[:,i]\mathbf{e}_i=\mathcal{E}_{mask}[:, i] and the per-pixel embedding at position (h,w)(h, w) as phw=Epixel[:,h,w]\mathbf{p}_{hw}=\mathcal{E}_{pixel}[:, h, w]; then

mi[h,w]=sigmoid(ei⊤ phw)m_i[h, w] = \text{sigmoid}\big(\mathbf{e}_i^{\top}\,\mathbf{p}_{hw}\big)

The ii-th mask embedding takes a dot product with every pixel's embedding; the more similar they are, the higher the probability that the pixel belongs to piece ii. Doing this once for each of the 100 mask embeddings over the 128×128128\times128 pixels gives 100×128×128100\times128\times128 masks.

Each mask goes through its own sigmoid, so the masks aren't mutually exclusive, and the same pixel can be claimed by several masks at once. The authors tried forcing exclusivity with a softmax, and it worked worse.

This is a lot like Mask R-CNN's mask branch, with two differences. Mask R-CNN predicts a small mask separately inside each box; MaskFormer computes the per-pixel embeddings only once for the whole image, shared by all 100 queries. And because it needs no boxes, it can handle "stuff" categories like sky and road that are hard to describe with a box.

Inference

Once trained, how do you get a semantic segmentation map out of 100 (class, mask) pairs?

The authors tested two ways. The first is hard assignment. Each pixel goes to the pair with the highest "class probability × mask probability," and regions of the same class are then merged. Panoptic segmentation uses this one, telling different regions of the same class apart by their query index.

The second is meant only for semantic segmentation; it multiplies each pair's class probabilities by its mask and adds them all up:

y^[h,w]=arg⁡max⁡c∈{1,…,K}∑i=1Npi(c)⋅mi[h,w]\hat{y}[h,w] = \arg\max_{c\in\{1,\dots,K\}} \sum_{i=1}^{N} p_i(c)\cdot m_i[h,w]

The official implementation is a single line of einsum:

python
def semantic_inference(self, mask_cls, mask_pred):
    mask_cls = F.softmax(mask_cls, dim=-1)[..., :-1]
    mask_pred = mask_pred.sigmoid()
    semseg = torch.einsum("qc,qhw->chw", mask_cls, mask_pred)
    return semseg

mask_cls is 100×151100\times151; dropping the last column, ∅\varnothing, leaves 100×150100\times150. mask_pred is 100×128×128100\times128\times128. The einsum sums out the query dimension and outputs 150×128×128150\times128\times128, exactly the same shape as per-pixel classification; take the argmax and you have the answer.

The second way beats hard assignment. But if you turn it around and train with cross-entropy directly on these summed per-pixel probabilities, the results are poor. The authors suspect that the gradient then gets spread evenly across every query, which makes training hard. Training uses the set loss; only at inference is the output converted back to per-pixel form.

The authors also note that which inference method to use depends on the evaluation metric, not on the task.

Discussion

Start with the Metrics

The standard metric for semantic segmentation is mIoU. It's computed pixel by pixel, which matches the per-pixel classification training objective exactly, and large objects, covering more pixels, carry more weight.

To bring out the difference between the two approaches, the authors also report PQSt\text{PQ}^{\text{St}} in their ablations. PQ (panoptic quality) is the metric for panoptic segmentation and works per region. Predicted and ground-truth regions are first matched at an IoU above 0.5, and the score then combines the mean IoU of the matched regions with the rate of successful matches. PQSt\text{PQ}^{\text{St}} treats every class as stuff, so every region carries the same weight regardless of size, and getting a small thing wrong counts too.

The Real Difference Is the Question

To keep things fair, the authors built two per-pixel baselines. PerPixelBaseline is MaskFormer's pixel-level module with a classifier attached directly; PerPixelBaseline+ adds the Transformer module and the MLP as well, so its only difference from MaskFormer is per-pixel classification versus mask classification.

Table 4 of the paper takes the difference apart with ResNet-50 on ADE20K, all three with 150 queries:

ModelmIoUPQSt\text{PQ}^{\text{St}}
PerPixelBaseline+41.928.3
MaskFormer (fixed matching)43.730.3
MaskFormer (bipartite matching)44.233.4

The second row is fixed matching with N=KN=K, where the ii-th query is responsible for the ii-th class; it differs from per-pixel classification almost only in how the question is posed. That alone adds 1.8 mIoU. The authors also tried giving PerPixelBaseline+ the same focal-plus-dice loss, with no improvement, so the gain comes from the question, not from the loss.

Switching to bipartite matching adds another 0.5 mIoU and 3.1 PQSt\text{PQ}^{\text{St}}. Bipartite matching frees the queries from being tied to a particular class, so they can output fewer masks than there are classes.

More Classes, Bigger Gap

Table 2 of the paper compares the two on four datasets (mIoU, with PQSt\text{PQ}^{\text{St}} in parentheses):

Dataset (classes)PerPixelBaseline+MaskFormer
Cityscapes (19)78.5 (60.2)78.5 (63.1)
ADE20K (150)41.9 (28.3)44.5 (33.4)
COCO-Stuff-10K (171)34.2 (24.6)37.1 (28.9)
ADE20K-Full (847)13.9 (9.0)17.4 (11.9)

The more classes there are, the bigger MaskFormer's win. On ADE20K-Full, with 847 classes, the gap is 3.5 points.

Cityscapes has only 19 classes; mIoU ties, yet PQSt\text{PQ}^{\text{St}} is 2.9 higher. Breaking this down further, the authors found MaskFormer better at recognition (getting the class right) and worse at pixel-level mask quality. On datasets with few classes, where recognition is easy, the bottleneck for mask classification is how precisely the boundaries are drawn.

How Many Queries?

ADE20K has 150 classes, COCO-Stuff 171 and ADE20K-Full 847, yet 100 queries works best for all of them. Just 20 queries already beat the per-pixel baseline; going up to 1000 makes things worse, with ADE20K dropping from 44.5 to 35.4.

Counting over the training sets, the authors found only 8.2 classes per image on average (ADE20K), 6.6 (COCO-Stuff-10K) and 9.1 (ADE20K-Full). The number of queries has to cover the regions that appear together in one image, not the total number of classes in the dataset. They also looked at which classes each query handles. Some queries specialize in classes that look alike (house and building), while others cover completely unrelated classes at once (water and sofa), and no obvious pattern emerges.

Against the Best Methods

On the ADE20K validation set (Table 1 of the paper), with the same ResNet-101c backbone, MaskFormer reaches 48.1% with multi-scale testing and DeepLabV3+ 46.4%. With an ImageNet-22K-pretrained Swin-L, MaskFormer reaches 55.6%, 2.1 above Swin-UperNet with the same backbone (53.5%), while parameters drop from 234M to 212M and FLOPs from 647G to 375G.

Read the speeds with care. A footnote in the paper specifically says that fps figures from different sources were measured in different environments and shouldn't be compared with one another.

Panoptic Segmentation

With the same model, the same losses and the same training procedure, simply switching the annotations from "one mask per class" to "one mask per object" lets it do panoptic segmentation. On COCO panoptic val (Table 3 of the paper), MaskFormer with ResNet-50 plus a 6-layer Transformer encoder gets 46.5 PQ, against 43.4 for DETR with the same architecture; the gain comes mainly from stuff classes. With Swin-L it reaches 52.7 PQ, 1.6 above the best method of the time, Max-DeepLab (51.1), and Max-DeepLab needs several auxiliary losses.

The last set of experiments (Table 5 of the paper) separates MaskFormer from DETR. Give MaskFormer a box prediction head and match by boxes, and PQ is 43.7, about the same as DETR's 43.4; switch back to matching by masks, and it's 46.5. The difference lies mainly in the matching. Boxes are especially poor for stuff classes; for regions like sky and road that sprawl across the whole image, a box carries almost no information.

Conclusion

MaskFormer didn't invent a new module; what it changed was the question. Semantic segmentation doesn't have to make every pixel guess its own class; you can cut the image into a few pieces first and then name each piece. Swap out the final classification head and any per-pixel segmentation model can be converted this way, and semantic and panoptic segmentation can share one model and one loss.

The more classes there are, the more this formulation pays off, with 3.5 extra points on the 847-class ADE20K-Full; on Cityscapes, with only 19 classes, it ties, and its boundaries come out worse than per-pixel classification's. The set loss for training and the one-line einsum back to per-pixel probabilities at inference were carried over by Mask2Former exactly as they were.

Mask2Former turned the Cityscapes tie around five months later. Its multi-scale result is 84.5 mIoU, slightly above the per-pixel SegFormer-B5 (84.0).