Back to paper library
arXiv 2021CVPR 2022SegmentationPaper notes

Mask2Former

Out of Sight, Out of Mind

Original paper

Masked-attention Mask Transformer for Universal Image Segmentation

Paper authors

Bowen Cheng · Ishan Misra · Alexander G. Schwing · Alexander Kirillov · Rohit Girdhar

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}
}
On this page

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

Original Figure 2: Mask2Former overview. On the left are the backbone, the pixel decoder and the Transformer decoder; the pixel decoder outputs features at four resolutions, from small to large, three of which connect in turn to three layers of the Transformer decoder, while the highest-resolution one is multiplied with the decoder's output to give masks, and the decoder's output also feeds the class prediction; the group of three layers repeats L times. On the right is a close-up of the inside of one decoder layer, from bottom to top: masked attention (image features as K and V, query features as Q, with a mask as an additional input), add & norm, self-attention, add & norm, FFN, add & norm.
Original Figure 2, Cheng et al., from PDF page 3, arXiv license, scholarly quotation.

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 ll, the NN queries Xl∈RN×CX_l\in\mathbb{R}^{N\times C} read the image features:

Xl=softmax(QlKl⊤) Vl+Xl−1X_l = \text{softmax}(Q_l K_l^{\top})\,V_l + X_{l-1}

QlQ_l is projected from the previous layer's queries, and KlK_l and VlV_l are projected from the image features, which have HlWlH_l W_l 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:

Xl=softmax(Ml−1+QlKl⊤) Vl+Xl−1X_l = \text{softmax}(\mathcal{M}_{l-1} + Q_l K_l^{\top})\,V_l + X_{l-1} Ml−1(x,y)={0if Ml−1(x,y)=1−∞otherwise\mathcal{M}_{l-1}(x, y) = \begin{cases} 0 & \text{if } M_{l-1}(x, y) = 1 \\ -\infty & \text{otherwise} \end{cases}

Ml−1M_{l-1} is the mask predicted by the previous decoder layer, resized to the resolution of KlK_l and binarized at a threshold of 0.5. Positions outside the mask get −∞-\infty 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 M0M_0 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:

python
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:

python
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, 1/321/32, 1/161/16 and 1/81/8. Decoder layer 1 looks at 1/321/32, layer 2 at 1/161/16, layer 3 at 1/81/8, layer 4 goes back to 1/321/32, 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 L=3L=3 times, for 9 decoder layers in total.

The highest-resolution 1/41/4 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:

  1. 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.
  2. 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.
  3. 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 K=12544K=12544 points (112×112112\times112). 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:

SettingAPPQmIoU
Mask2Former43.751.947.2
w/o masked attention37.847.145.5
w/o high-res features41.550.246.1
w/o learnable query features42.951.245.4
w/o cross-attention first43.251.646.3
Dropout kept43.051.347.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 1/81/8 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

Original Figure 3: the top half has three rows of images (a surfboard, zebras, doughnuts), and the four columns in each row are masks predicted by the same set of learnable queries before they enter the decoder, with each column marking in red the object one query picks out; the bar chart at bottom left shows AR@100 on COCO val2017, 50.3 for the learnable queries before the decoder and 56.8, 57.4 and 57.7 at decoder layers 3, 6 and 9; the bottom right illustrates the learnable queries being multiplied directly with the pixel decoder's output to produce masks.
Original Figure 3, Cheng et al., from PDF page 8, arXiv license, scholarly quotation.

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; M0M_0 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.