Masked-attention Mask Transformer for Universal Image Segmentation
- Publication
- CVPR 2022Conference
- First submitted to arXiv
- arXiv:2112.01527
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{segmentationmask2former2021,
title = {{Masked-attention Mask Transformer for Universal Image Segmentation}},
author = {Bowen Cheng and Ishan Misra and Alexander G. Schwing and Alexander Kirillov and Rohit Girdhar},
year = {2021},
eprint = {2112.01527},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2112.01527}
}
MaskFormer showed that semantic segmentation and panoptic segmentation can be done with the same mask classification model and the same set of losses. It set the best result of its time on ADE20K and beat DETR on COCO panoptic segmentation too.
But there was one assignment it never handed in, and that was instance segmentation.
The authors of this paper are almost the same team as MaskFormer, joined by Ishan Misra and Rohit Girdhar of FAIR. On the very first page they ask why, if a universal architecture can handle every segmentation task, everyone is still building a specialized model for each task.
Defining the Problem
Segmentation tasks differ only in "how to group." Semantic segmentation groups by class, instance segmentation by individual object, and panoptic segmentation needs both. Yet before Mask2Former, the best models for the three tasks looked completely different. Semantic segmentation used FCN-style per-pixel classification, and instance segmentation used Mask R-CNN-style boxes plus masks.
Universal architectures like DETR, MaskFormer and K-Net tried to unify all three in one set-prediction framework, but their actual results couldn't keep up with specialized models. The authors' example is instance segmentation, where the best universal architecture trailed the specialized SOTA by more than 9 AP.
Training cost is another problem. MaskFormer needs 300 epochs of training on COCO to reach 40.1 AP, and a single 32GB GPU fits only one image; the specialized Swin-HTC++ needs just 72 epochs and does better.
The authors noticed something else as well. Many "panoptic" architectures report only panoptic segmentation scores, but the panoptic metric doesn't evaluate how predictions are ranked, so a model's instance segmentation performance can't be read off its panoptic score. This paper therefore holds itself to handing in results on all three tasks.
Solving the Problem

The overall framework is the same as MaskFormer's. The backbone extracts features, the pixel decoder upsamples them into per-pixel embeddings, the Transformer decoder has a set of queries read the image features, and finally each query outputs a class and a mask.
What changes is the Transformer decoder on the right. The authors changed four things, namely masked attention, multi-scale features, three small optimization tweaks, and a point-sampled loss during training.
Masked attention
First, recall the cross-attention in the DETR and MaskFormer decoders. At layer , the queries read the image features:
is projected from the previous layer's queries, and and are projected from the image features, which have positions. Every query can see every position of the whole image.
Earlier work had already pointed to this as the reason Transformer detectors converge slowly. Cross-attention starts out looking at the whole image, and it takes a long time to learn to focus its attention on the regions where objects are. The authors' hypothesis is that local features are enough for a query, and context can be left to the self-attention among queries to exchange.
So masked attention adds a mask to the attention scores:
is the mask predicted by the previous decoder layer, resized to the resolution of and binarized at a threshold of 0.5. Positions outside the mask get added, so after the softmax their weights become 0.
Take a single query. Suppose that at layer 3 this query predicts a mask that roughly covers the zebra on the right of the frame. At layer 4, its cross-attention can only see the pixels on that zebra; the background and the other two zebras are invisible to it. Having looked, it updates itself and predicts a more accurate mask, which goes on to layer 5. Mask and attention correct each other this way, layer by layer.
Where does the mask for the first layer come from? The authors have the queries predict a mask once before they enter the decoder.
In the official implementation, this attention mask is produced along the way by the prediction head at every layer:
attn_mask = F.interpolate(outputs_mask, size=attn_mask_target_size, mode="bilinear", align_corners=False)
attn_mask = (attn_mask.sigmoid().flatten(2).unsqueeze(1).repeat(1, self.num_heads, 1, 1).flatten(0, 1) < 0.5).bool()
PyTorch attention masks use True to mean "not allowed to look," so the condition is a probability below 0.5. Before the next layer's cross-attention, there's one more line as a safeguard:
attn_mask[torch.where(attn_mask.sum(-1) == attn_mask.shape[-1])] = False
If a query's mask is empty, its whole row is True, and the softmax denominator would be zero. This line resets the whole row to False, so the query falls back to ordinary cross-attention and looks at the whole image.
Multi-Scale, but One Scale at a Time
High-resolution features help with small objects, but the cost of cross-attention is proportional to the number of positions in the feature map.
The authors' answer is to take turns. The pixel decoder outputs features at three resolutions, , and . Decoder layer 1 looks at , layer 2 at , layer 3 at , layer 4 goes back to , and so on. Each resolution gets a sinusoidal positional encoding plus a learnable scale embedding, so the queries know which level they're looking at. The group of three layers repeats times, for 9 decoder layers in total.
The highest-resolution features aren't used for attention; they're only used in the dot product with the queries to produce masks.
Three Small Changes
None of these three changes adds computation:
- Cross-attention first. In a standard decoder layer, self-attention comes first. But queries at the first layer haven't seen the image yet, so self-attention among them has no information to exchange. So they read the image first, then exchange.
- Learnable query features too. DETR initializes the query features to zero, and only the positional embeddings are learnable. Mask2Former makes the query features themselves learnable as well, and supervises them with the mask loss before they even enter the decoder. The authors found that this set of queries acts a lot like a region proposal network (RPN), proposing decent candidate masks right from the start.
- Dropout removed. The authors found dropout unnecessary, and it usually made results worse.
Loss on Just a Few Points
One reason MaskFormer eats memory is that the mask loss is computed on full high-resolution masks, with each of the 100 queries compared pixel by pixel against the ground-truth mask.
Mask2Former borrows the idea from PointRend and computes the loss on only points (). For bipartite matching, all predictions and annotations use the same set of uniformly sampled points; for the final loss, each prediction–annotation pair gets its own set of points, with importance sampling concentrating them in uncertain regions. This brings training memory down from 18GB to 6GB per image.
As for the remaining settings, the pixel decoder uses 6 layers of multi-scale deformable attention (MSDeformAttn) by default, the mask loss becomes binary cross-entropy plus dice loss, and every decoder layer, as well as the queries before they enter the decoder, gets an auxiliary loss. Training on COCO runs for 50 epochs with large-scale jittering (LSJ) data augmentation.
Discussion
What Each Part Is Worth
All ablations use ResNet-50 and look at the three tasks at once (AP for COCO instance segmentation, PQ for COCO panoptic segmentation and mIoU for ADE20K semantic segmentation). Tables 4a and 4b of the paper remove one part at a time:
| Setting | AP | PQ | mIoU |
|---|---|---|---|
| Mask2Former | 43.7 | 51.9 | 47.2 |
| w/o masked attention | 37.8 | 47.1 | 45.5 |
| w/o high-res features | 41.5 | 50.2 | 46.1 |
| w/o learnable query features | 42.9 | 51.2 | 45.4 |
| w/o cross-attention first | 43.2 | 51.6 | 46.3 |
| Dropout kept | 43.0 | 51.3 | 47.2 |
Masked attention is the biggest item. Without it, instance segmentation loses 5.9 AP and panoptic 4.8 PQ, while semantic loses only 1.7. Instance and panoptic segmentation have to separate neighboring individuals, so having each query keep its eyes on its own piece helps them especially.
Other cross-attention variants were compared too (Table 4c of the paper). Standard cross-attention gets 37.8 AP, SMCA 37.9, the mask pooling used by K-Net (averaging the features inside the mask) 43.1, and masked attention 43.7. On all three tasks, masked attention is the best.
For multi-scale (Table 4d of the paper), a single scale gets 44.0 AP at 239 GFLOPs; taking turns over three scales gets 43.7 AP at 226 GFLOPs; feeding all three scales to every layer gets 44.0 AP at 247 GFLOPs. Taking turns reaches about the same result with less computation.
The point-sampled loss (Table 5 of the paper) saves 3× memory without hurting results. Using points for matching as well improves all three tasks, with AP going from 41.0 to 43.7.
The pixel decoder brought an unexpected finding too (Table 4e of the paper). BiFPN does well on instance segmentation, FaPN does well on semantic segmentation, and MSDeformAttn is the best on all three tasks. The authors take this as evidence that a module designed for one task won't necessarily do as well on other tasks.
Learnable Queries Are Proposals

The masks in the top half all come from queries that haven't entered the decoder yet. They're just learned vectors that haven't done any attention on this image, and they can already pick out a single surfboard, zebra or doughnut.
The bar chart at bottom left quantifies this with class-agnostic recall, AR@100. The queries before the decoder score 50.3, jump to 56.8 after 3 decoder layers, and gain only 0.9 more over the following 6 layers. This also explains why masked attention can be used from the very first layer; is already a decent proposal by itself.
Results on the Three Tasks
On COCO panoptic segmentation (Table 1 of the paper), Mask2Former with ResNet-50 gets 51.9 PQ against MaskFormer's 46.5, and it trains for only 50 epochs where MaskFormer needs 300. The Swin-L backbone version with 200 queries gets 57.8 PQ, 5.1 above MaskFormer and 3.2 above the concurrent K-Net.
On COCO instance segmentation (Table 2 of the paper), the ResNet-50 version gets 43.7 AP, against 42.5 for a Mask R-CNN trained for 400 epochs with large-scale jittering. The Swin-L version gets 50.1 AP, 0.6 above the specialized Swin-HTC++; on boundary AP, which measures boundary quality, it's 36.2 versus 34.1, 2.1 higher. With high-resolution mask prediction, the boundaries come out finer.
On ADE20K semantic segmentation (Table 3 of the paper), a Swin-L backbone with the FaPN pixel decoder reaches 57.7 mIoU with multi-scale testing, above the strongest specialized model of the time, BEiT-UperNet (57.0).
On the Cityscapes validation set (Table 6 of the paper), the Swin-B version gets 84.5 mIoU on semantic segmentation with multi-scale testing, against 84.0 for SegFormer-B5.
Still Trained Separately
In the limitations section, the authors admit that while Mask2Former's architecture is universal, each task still has to be trained separately. Table 7 of the paper takes models trained only on panoptic annotations and evaluates them on instance and semantic segmentation; in four of the six comparisons, the results come out slightly lower than those of the same model trained specifically on the corresponding annotations. On Cityscapes, for example, the panoptic model gets 77.5 mIoU on semantic segmentation, and the semantic model 79.4.
Another weak spot is small objects. For the Swin-L instance segmentation version, small-object AP is 29.9, against 31.0 for Swin-HTC++. The authors believe the multi-scale features aren't yet fully exploited, and loss designs aimed at small objects still have room to improve.
Conclusion
Masked attention is Mask2Former's main change, with each query looking only within the mask it predicted at the previous layer. Add multi-scale features read in turn, three small changes that add no computation and the point-sampled loss, and it became the first universal architecture to match or beat specialized models on all three tasks, panoptic, instance and semantic; 50 epochs of training on COCO are enough, and training memory per image falls from 18GB to 6GB. Still, each of the three tasks has to be trained on its own.
If you're reading the code, start with forward_prediction_heads; each layer's class, mask and the attention mask for the next layer are all produced there. Before entering cross-attention, there's also the safeguard line the paper never mentions. When a query's mask is completely empty, it falls back to looking at the whole image, so the softmax denominator doesn't become zero and produce NaN.
If you write your own masked attention, remember to copy that line along with it.