Per-Pixel Classification is Not All You Need for Semantic Segmentation
- 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}
}
Ever since FCN, semantic segmentation has been treated as per-pixel classification. Each pixel outputs a probability distribution over 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

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 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 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 , where is a probability over classes (with one extra, "no object" ) and is an 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 , so the -th prediction is always responsible for the -th class, and if that class doesn't appear in the image, it is matched to . 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 with annotation is .
Once matched, the loss is
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. follows DETR and is a weighted sum of focal loss and dice loss.
Solving the Problem

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 input, a ResNet-50 backbone, 150 classes and 100 queries.
Pixel-Level Module
The backbone outputs a stride-32 feature map ; a image gives 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 convolution, going all the way from stride 32 down to stride 4; a final convolution outputs the per-pixel embeddings .
In our example, is , a 256-dimensional vector at every pixel position.
A per-pixel classification model would attach a classifier right after this step and output a 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 ( positions). The output 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 . 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 ), giving .
- Mask: an MLP with two hidden layers turns it into a 256-dimensional mask embedding , giving .
The masks come from a dot product. Write the -th mask embedding as and the per-pixel embedding at position as ; then
The -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 . Doing this once for each of the 100 mask embeddings over the pixels gives 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:
The official implementation is a single line of einsum:
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 ; dropping the last column, , leaves . mask_pred is . The einsum sums out the query dimension and outputs , 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 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. 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:
| Model | mIoU | |
|---|---|---|
| PerPixelBaseline+ | 41.9 | 28.3 |
| MaskFormer (fixed matching) | 43.7 | 30.3 |
| MaskFormer (bipartite matching) | 44.2 | 33.4 |
The second row is fixed matching with , where the -th query is responsible for the -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 . 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 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 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).