Sub topic 15
Unified mask classification with transformers
This chapter assumes you know how Mask R-CNN and per-pixel semantic segmentation work, and that you are comfortable with attention and the Hungarian algorithm at a high level. It covers MaskFormer and Mask2Former, which handle semantic, instance, and panoptic segmentation with one model and one loss.
Two ways to frame segmentation
Earlier chapters used two framings:
- Per-pixel classification. Encoder-decoder and dilated networks predict a class distribution at every pixel. This fits semantic segmentation. It cannot separate two touching cars, because both pixels get the label "car".
- Detect-then-segment. Mask R-CNN predicts boxes and then one mask per box. This gives instances, but stuff classes such as sky or road need a separate semantic branch, and the merge step needs hand-written rules.
Mask classification is a third framing. The model predicts a set of N binary masks. Each mask gets one class label, or a "no object" label. A semantic map is a set of masks, one per class present. An instance result is a set of masks, one per object. A panoptic result is a set of masks that do not overlap. The same output format therefore covers all three tasks, and only the post-processing differs.
Architecture
MaskFormer (Cheng et al., 2021) and Mask2Former (2022) share a three-part design.
- Backbone and pixel decoder. A CNN or transformer backbone produces multi-scale features. The pixel decoder upsamples them into per-pixel embeddings of shape (C, H/4, W/4).
- Transformer decoder. N learned query vectors (typically 100) attend to the image features. Each query ends up describing one candidate segment.
- Two heads. A linear layer maps each query to K+1 class logits, where K is the number of real classes and the extra class means "no object". An MLP maps each query to a mask embedding. The mask logits are the dot product of that embedding with every pixel embedding. A sigmoid turns them into a soft mask.
Mask2Former changes the decoder in two ways. Its masked attention restricts each query's cross-attention to the foreground region of its own mask from the previous layer. This makes training converge faster. It also feeds the decoder multi-scale features, one scale per layer, which helps small segments.
Training: set prediction and matching
The model outputs N predictions, but an image has only a few ground-truth segments. There is no natural order that pairs predictions with ground truth. Training solves this with bipartite matching, as in DETR:
- Compute a cost for every (prediction, ground-truth segment) pair. The cost combines the class probability of the true class with a mask overlap term.
- Run the Hungarian algorithm to find the one-to-one assignment with the lowest total cost.
- Compute the loss on the matched pairs. Matched predictions are trained toward their segment's class and mask. Unmatched predictions are trained toward "no object".
The loss is a classification cross-entropy plus a mask loss. The mask loss is binary cross-entropy (focal loss in MaskFormer) plus the Dice loss from the losses chapter. Dice keeps small segments from being drowned out by background pixels. Mask2Former computes the mask loss at randomly sampled points instead of every pixel, which cuts memory sharply.
Because matching is one-to-one, the model learns not to emit duplicate masks. This removes the need for non-maximum suppression.
Inference: one output, three tasks
The raw output is the same for every task. Post-processing selects the task.
Semantic. For each class, sum the soft masks of all queries, weighted by that query's probability for the class. Then take the argmax over classes at each pixel.
Panoptic. Keep queries whose best class is not "no object" and whose score exceeds a threshold. Assign each pixel to the surviving query with the highest score times mask probability. Drop a segment if too little of its original mask survives. This removes fragments and resolves overlaps without a separate merging rule.
Instance. Rank queries by class score times average mask score, and keep the top ones. Overlap is allowed.
import torch
def semantic_inference(class_logits, mask_logits):
# class_logits: (Q, K+1), mask_logits: (Q, H, W)
probs = class_logits.softmax(-1)[..., :-1] # drop the "no object" column
masks = mask_logits.sigmoid()
return torch.einsum("qk,qhw->khw", probs, masks) # (K, H, W) class scores
def panoptic_inference(class_logits, mask_logits, score_thresh=0.5, overlap_thresh=0.8):
num_classes = class_logits.shape[-1] - 1
scores, labels = class_logits.softmax(-1).max(-1)
keep = (labels != num_classes) & (scores > score_thresh)
scores, labels = scores[keep], labels[keep]
masks = mask_logits[keep].sigmoid()
h, w = mask_logits.shape[-2:]
seg_map = torch.zeros(h, w, dtype=torch.long) # 0 = void
segments = []
if masks.shape[0] == 0:
return seg_map, segments
owner = (scores[:, None, None] * masks).argmax(0) # winning query per pixel
for k in range(masks.shape[0]):
original = masks[k] >= 0.5
claimed = (owner == k) & original
if original.sum() == 0 or claimed.sum() == 0:
continue
if claimed.sum() / original.sum() < overlap_thresh:
continue # most of this mask was taken by other segments
sid = len(segments) + 1
seg_map[claimed] = sid
segments.append({"id": sid, "label": int(labels[k]), "score": float(scores[k])})
return seg_map, segments
torch.manual_seed(0)
Q, K, H, W = 10, 5, 32, 32
class_logits = torch.randn(Q, K + 1)
mask_logits = torch.randn(Q, H, W)
print(semantic_inference(class_logits, mask_logits).argmax(0).shape)
seg_map, segments = panoptic_inference(class_logits, mask_logits, score_thresh=0.2)
print(seg_map.shape, segments)With random inputs the segments are meaningless. The code only shows the tensor shapes and the claiming logic. In practice, Hugging Face transformers provides pretrained models (Mask2FormerForUniversalSegmentation) and ready-made post-processing functions for all three tasks.
Trade-offs and failure modes
| Aspect | Mask classification | Per-pixel or Mask R-CNN |
|---|---|---|
| Task coverage | One architecture and loss for all three tasks | Separate designs per task |
| Duplicate handling | Learned through matching | NMS or hand-written merging |
| Training cost | Matching and a long schedule | Usually shorter |
| Small objects | Needs multi-scale features | Box-based methods are mature |
| Query budget | Fixed N caps segments per image | Variable number of proposals |
Common errors:
- Too few queries. If an image contains more segments than N, some are missed. Dense scenes need a larger N.
- Forgetting the "no object" column. Including it in the semantic sum adds background mass to every pixel. Drop it, as the code above does.
- Thresholds copied between tasks. The score and overlap thresholds in panoptic inference change how many segments survive. Tune them on a validation set.
- Wrong mask resolution. Masks are predicted at 1/4 resolution. Upsample the mask logits to the image size before thresholding, not after.
Exercise
A trained Mask2Former with 100 queries produces, for one image, 100 masks with class probabilities. Describe how you would turn this into (a) a semantic map and (b) a panoptic map. Why does the panoptic version need an overlap threshold?
Show answer
(a) Drop the "no object" probability, weight each query's sigmoid mask by its class probabilities, sum over queries to get K class score maps, and take the argmax over classes at each pixel. (b) Discard queries predicted as "no object" or with a low score. Assign each pixel to the remaining query with the highest score times mask probability, so segments cannot overlap. The overlap threshold removes a segment when most of its original mask was claimed by higher-scoring queries. Otherwise it would remain as a small fragment that is not a real object.