· computer-vision · segmentation · transformers · paper-dissection

Mask2Former, Dissected

In short. Image segmentation labels every pixel of an image. There are three versions of the task, semantic, instance and panoptic (§1). By late 2021, universal models, built to handle all three, did well on semantic and panoptic segmentation. But on instance segmentation, which separates individual objects, they still lost to specialized systems. MaskFormer, Mask2Former’s direct predecessor, trailed the best of them by over 9 AP, the standard instance score. Mask2Former [Cheng et al. 2022] kept MaskFormer’s core idea, one mask and one class per learned query, and rebuilt its decoder and its training recipe. It closed the gap, at 50.1 AP against 49.5 for the specialized Swin-HTC++, and reported the best results to date on the other two versions (§8).

How it works, in five steps.

  1. The model keeps a fixed set of learned vectors called queries, 100 by default. Each query predicts one region of the image as a mask, and what that region is as a class (§2).
  2. A query makes its mask by taking the dot product of its vector with the vector of every pixel. A high value means the pixel belongs to the query’s region (§3).
  3. In training, each real object is paired with exactly one query, which learns to predict it. A pair’s cost measures how badly the query’s class and mask fit the object, and the pairing with the lowest total cost wins. Unpaired queries learn to predict “no object” (§4).
  4. Nine decoder layers refine the queries. In each layer, a query reads image features only inside the mask it predicted at the previous layer, so the background can no longer drown out its object. This is masked attention, the paper’s main idea (§5).
  5. Two more ideas make this affordable. The layers take turns reading coarse and fine feature maps, and the mask losses are computed on 12,544 sampled points instead of every pixel, which cuts training memory from 18 GB to 6 GB per image (§6).

Steps 1 to 3 come from MaskFormer, and steps 4 and 5 are new. Together they form a loop: every layer’s mask is trained against the true mask, and each trained mask decides where the next layer looks.

Image Backbone finds features ResNet or Swin Pixel decoder 3 feature sizes + pixel embeddings 1/32 1/16 1/8 Transformer decoder queries read the features 9 layers: 1/32, 1/16, 1/8 cycled three times N learned queries Class what it is Mask where it is each mask limits where the next layer looks pixel embedding map: a mask is each query compared with every pixel here Image Backbone finds features ResNet or Swin Pixel decoder 3 feature sizes + pixel embeddings 1/32 1/16 1/8 Transformer decoder queries read the features 9 layers: 1/32, 1/16, 1/8 cycled three times N learned queries Class what it is Mask where it is each mask limits where the next layer looks pixel embedding map: a mask is each query compared with every pixel here
Overview. N learned queries read the image's features in nine decoder layers, cycling through three resolutions. Each query predicts a class and a mask, and each mask limits where the next layer looks.

How to read this.

  • In five minutes: the five steps and the picture above, then Fig. 2, Fig. 3, Fig. 4, Fig. 5 and Fig. 6, which show the steps in order.
  • If you know DETR and the segmentation metrics: start at §3. Mask2Former’s own changes are §5 to §7, and §7 ends with what each one is worth.
  • If any of this is new: start at §0, which builds every idea the rest uses. If attention and losses are familiar, start at §1.

Proofs and longer derivations are folded, and the main text never depends on them. In the figures, gold marks what the model predicts, green marks ground truth, and slate marks image features.

Contents
All symbols, for reference
symbolmeaning
I∈R3×H×WI \in \mathbb{R}^{3\times H\times W}input image. Hl×WlH_l \times W_l is the size of the feature map used at decoder layer ll
Ω\Omegathe pixel grid, the set of pixel locations of the map under discussion. ∣Ω∣\lvert\Omega\rvert is its size
CCshared feature dimension of queries and image features (256 in the reference implementation)
NNnumber of object queries (100 by default, 200 for the Swin-L panoptic and instance models)
KK, ∅\varnothingnumber of classes, and the “no-object” class appended to them. This KK is unrelated to §0’s key matrix
(mi,ci)(m_i, c_i)prediction ii, with a soft mask mi∈[0,1]H×Wm_i \in [0,1]^{H\times W} and class ci∈{1,…,K}∪{∅}c_i \in \{1,\dots,K\}\cup\{\varnothing\}
p^i(c)\hat p_i(c)predicted probability that query ii has class cc, from p^i=softmax⁡(Wcls qi+bcls)\hat p_i = \operatorname{softmax}(W_{\text{cls}}\, q_i + b_{\text{cls}}) with one output per class plus no-object
qi∈RCq_i \in \mathbb{R}^Cthe normalized feature of query ii that the class and mask heads read (§3)
π\pian assignment of predictions to targets, a permutation in SNS_N (§4)
Xl∈RN×C\mathbf{X}_l \in \mathbb{R}^{N\times C}query features after decoder layer ll. X0\mathbf{X}_0 are the learnable input query features
X~l\widetilde{\mathbf{X}}_lintermediate residual state immediately after adding the cross-attention output in layer ll, before LayerNorm and the remaining sublayers
Ql,Kl,Vl\mathbf{Q}_l, \mathbf{K}_l, \mathbf{V}_lattention projections. Ql∈RN×C\mathbf{Q}_l \in \mathbb{R}^{N\times C} comes from the queries, and Kl,Vl∈RHlWl×C\mathbf{K}_l,\mathbf{V}_l \in \mathbb{R}^{H_lW_l\times C} come from image features
ZlZ_lmask logits predicted at output ll, one logit map per query
Bl(i,x)B_l(i,x)binary gate for query ii at location xx, obtained by resizing ZlZ_l, applying the sigmoid, and thresholding at 0.50.5
Ml(i,x)\mathcal{M}_{l}(i,x)additive attention mask built from Bl(i,x)B_l(i,x). It is 00 on allowed locations and −∞-\infty elsewhere
Epixel\mathcal{E}_{\text{pixel}}per-pixel embeddings from the pixel decoder, at stride 4
σ(⋅)\sigma(\cdot)the logistic sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}), which maps real scores into (0,1)(0,1)
1[⋅]\mathbb{1}[\cdot]the indicator, with 1[P]=1\mathbb{1}[P] = 1 when condition PP holds and 00 otherwise
λce,λdice,λcls\lambda_{\text{ce}}, \lambda_{\text{dice}}, \lambda_{\text{cls}}Binary cross-entropy (BCE), Dice, and class-loss weights. Their values are 55, 55, and 22. The no-object class receives an additional 0.10.1 multiplier
KptK_{\text{pt}}number of sampled points for mask losses, 12,544=112212{,}544 = 112^2

0. The background you need

Mask2Former is built from a few standard ideas, one per paragraph below. Skip any you already know.

Feature maps. A neural network called a backbone turns the image into a smaller grid, where each cell holds a vector that summarizes a patch of the image. That grid is a feature map, and its stride is the shrink factor. At stride 32, a 1024 by 1024 image becomes a 32 by 32 grid, so each cell stands for a 32 by 32 patch. Small objects lose detail at that scale, which is why Mask2Former also reads finer maps (§6).

Embeddings and the dot product. An embedding is a learned vector whose direction carries meaning. Related inputs tend to point in similar directions. The dot product measures how much two vectors agree: multiply them entry by entry, then add. For example, (2,1)⋅(1,2)=4(2, 1)\cdot(1, 2) = 4, while (2,1)⋅(−1,2)=0(2, 1)\cdot(-1, 2) = 0. In general, for vectors uu and vv with angle θ\theta between them,

u⊤v=∑kukvk=∥u∥ ∥v∥cos⁡θ,u^\top v = \sum_k u_k v_k = \|u\|\,\|v\|\cos\theta,

where u⊤u^\top is uu written as a row and ∥u∥\|u\| is its length. The result is positive when the vectors point the same way, zero when they are perpendicular, and negative when they point apart. Mask2Former makes every mask this way (§3).

Softmax. Softmax turns a list of scores into weights that are positive and add up to 1. Take the scores 2.0, −0.6, −2.2 and 1.1. Exponentiating gives 7.39, 0.55, 0.11 and 3.00. Dividing each by their sum, 11.05, gives the weights 0.67, 0.05, 0.01 and 0.27. The largest score takes most of the weight, but no weight is exactly zero. In general, for scores z1,…,znz_1, \dots, z_n, which are also called logits,

wi=ezi∑jezj.w_i = \frac{e^{z_i}}{\sum_j e^{z_j}}.

The only way to give an option a weight of exactly 0 is a score of −∞-\infty, because e−∞=0e^{-\infty} = 0. The other weights still add up to 1. Masked attention in §5 is built on this.

Attention. Attention [Vaswani et al. 2017] lets one vector, the query, collect information from many others. Each image location carries two vectors, both computed from its features by learned linear maps. Its key is compared with the query, and its value is what it hands over. The dot product of the query with each key gives a score, softmax turns the scores into weights, and the output is the values mixed by those weights. Fig. 0 runs this on four locations of a photo, with the scores of the softmax example.

Fig. 0. Attention is a soft lookup: compare the query with each key, turn the scores into weights with softmax, then mix the values. The scores are made up for the example, and §5 reuses them.
The matrix form, for many queries at once

For many queries at once, stack the NN queries as the rows of a matrix QQ, and the keys and values of the nn locations as the rows of KK and VV. Every row holds dd numbers. Then

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤d)V,\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt d}\right)V,

where each row of QK⊤QK^\top holds one query’s scores, softmax turns each row into weights, and multiplying by VV mixes the values. Dividing by d\sqrt d keeps the scores from growing with the vector length dd. In practice the model runs several lookups in parallel, called heads, each with its own learned projections.

Transformer decoder layers. A decoder layer updates every query’s vector xx three times, each time adding the result to xx, which is called a residual connection. Leaving out normalization and projections, Mask2Former’s layer runs

x ← x+Attention⁡(x, image),x ← x+Attention⁡(x, x),x ← x+FFN⁡(x).x \,\leftarrow\, x + \operatorname{Attention}(x,\ \text{image}), \qquad x \,\leftarrow\, x + \operatorname{Attention}(x,\ x), \qquad x \,\leftarrow\, x + \operatorname{FFN}(x).

The first update is cross-attention, where the query reads the image. The second is self-attention, where the queries read each other, so they can coordinate, for example to avoid describing the same object twice. The third is a small feed-forward network (FFN) applied to each query on its own. Mask2Former stacks nine such layers.

Losses and gradients. A loss L\mathcal{L} is one number that measures how wrong the output is. Training nudges every weight against the gradient ∇wL\nabla_w \mathcal{L}, the direction in weight space that raises the loss fastest. Mask2Former’s loss is defined in §4.

1. Three ways to segment an image

Segmentation groups pixels and labels the groups. Datasets split categories into things, countable objects such as people and cars, and stuff, amorphous regions such as road and sky [Kirillov et al. 2019]. Fig. 1 shows one street scene segmented all three ways.

semantic sky road car one class per pixel: the two cars merge instance car 1 car 2 one mask per thing: sky and road left out panoptic sky road car 1 car 2 every pixel labeled, ids kept on things
Fig. 1. One street scene, three tasks.

Semantic segmentation gives every pixel a class, so two touching cars become one car region. Instance segmentation returns one mask per thing, each with a confidence score, and ignores stuff. Panoptic segmentation [Kirillov et al. 2019] does both: every pixel gets a class, and pixels of things also get an instance id.

How the tasks are scored. Each task has its own score, from 0 to 100, where higher is better: mIoU for semantic, AP for instance and PQ for panoptic segmentation. All three rest on intersection over union (IoU), the area two regions share divided by their combined area, which is 1 for identical regions and 0 for regions that do not touch.

The results in this article use two datasets: COCO [Lin et al. 2014] for instance and panoptic segmentation, and ADE20K [Zhou et al. 2017] for semantic segmentation.

The exact definitions are folded below.

How mIoU is computed

Accumulate the predicted and ground-truth pixels of each class cc over the whole evaluation set, as pixel sets PcP_c and GcG_c. Then

mIoU=1∣Ceval∣∑c∈Ceval∣Pc∩Gc∣∣Pc∪Gc∣,Ceval={c:∣Gc∣>0}\text{mIoU} = \frac{1}{|\mathcal{C}_{\mathrm{eval}}|}\sum_{c\in\mathcal{C}_{\mathrm{eval}}} \frac{|P_c \cap G_c|}{|P_c \cup G_c|}, \qquad \mathcal{C}_{\mathrm{eval}} = \{c : |G_c| > 0\}

[Everingham et al. 2015]. The average runs over the classes present in the ground truth, as in Detectron2’s evaluator, which also rules out the 0/00/0 case.

How COCO mask AP is computed

For each image and class, predictions are processed in descending score order. A prediction is a true positive when its best still-unclaimed ground truth of the same class in that image clears the current IoU threshold.

IoU(mˉi,g)=∑x∈Ωmˉi(x) g(x)∑x∈Ω(mˉi(x)+g(x)−mˉi(x) g(x)),i∈TP  ⟺  max⁡g∈GiIoU(mˉi,g)≥τ,\begin{gathered} \text{IoU}(\bar m_i, g) = \frac{\sum_{x\in\Omega} \bar m_i(x)\, g(x)}{\sum_{x\in\Omega} \big(\bar m_i(x) + g(x) - \bar m_i(x)\, g(x)\big)},\\[4pt] i \in \mathit{TP} \iff \max_{g \in \mathcal{G}_i} \text{IoU}(\bar m_i, g) \ge \tau, \end{gathered}

where the sums visit every pixel xx of the grid Ω\Omega. COCO receives binary masks. Mask2Former’s released inference code obtains mˉi(x)=1[mi(x)>0.5]\bar m_i(x) = \mathbb{1}[m_i(x) > 0.5], which is 11 on claimed pixels and 00 elsewhere. The ground-truth mask g(x)g(x) is also binary. On 0/10/1 values a product acts as an AND, so the numerator counts the intersection. The combination mˉi(x)+g(x)−mˉi(x) g(x)\bar m_i(x) + g(x) - \bar m_i(x)\, g(x) acts as an OR, so the denominator counts the union. Finally Gi\mathcal{G}_i holds the ground truths of the same class and image that remain unclaimed when prediction ii takes its turn. If Gi\mathcal{G}_i is empty the max is −∞-\infty, an automatic false positive. Once a true positive claims a ground truth, later duplicates become false positives, which makes confidence ranking matter. Everything else is a false positive.

After matching within each image, COCO gathers the detections for each class across the dataset and sorts them by score. At any score cutoff, precision is the fraction of kept predictions that are true positives, and recall is the fraction of ground truths recovered. Sweeping the cutoff traces the precision-recall curve. COCO summarizes its interpolated precision at 101 recall levels and averages over ten IoU thresholds [Lin et al. 2014]:

P=∣TP∣∣TP∣+∣FP∣,R=∣TP∣∣G∣,P = \frac{|\mathit{TP}|}{|\mathit{TP}| + |\mathit{FP}|}, \qquad R = \frac{|\mathit{TP}|}{|G|}, AP=1∣T∣∑τ∈T1101∑r∈{0,0.01,…,1}pτinterp(r).\text{AP} = \frac{1}{|\mathcal{T}|}\sum_{\tau\in\mathcal{T}} \frac{1}{101}\sum_{r\in\{0,0.01,\ldots,1\}} p_\tau^{\mathrm{interp}}(r).

Here ∣G∣|G| is the number of ground-truth masks, T={0.50,0.55,…,0.95}\mathcal{T} = \{0.50, 0.55, \dots, 0.95\}, and pτinterp(r)=max⁡r′≥rpτ(r′)p_\tau^{\mathrm{interp}}(r) = \max_{r' \ge r} p_\tau(r') is the interpolated precision, the best precision the curve reaches at recall rr or beyond. This is the per-category AP. COCO then averages over categories. Recall levels the curve never reaches count as zero precision. A category with no ground-truth instances in the evaluation set is excluded from the mean. This sketch omits crowd and ignore bookkeeping and the per-image detection cap.

How PQ is computed, and why its matches are unique

Evaluation first sets aside void pixels, which carry no label, and crowd regions, which group objects the annotators could not separate. Write TP\mathit{TP} for matched pairs, FP\mathit{FP} for unmatched predictions, and FN\mathit{FN} for unmatched ground-truth segments. Then

PQ=∑(p,g)∈TPIoU(p,g)∣TP∣+12∣FP∣+12∣FN∣=∑(p,g)∈TPIoU(p,g)∣TP∣⏟SQ×∣TP∣∣TP∣+12∣FP∣+12∣FN∣⏟RQ.\text{PQ} = \frac{\sum_{(p,g)\in \mathit{TP}}\text{IoU}(p,g)}{|\mathit{TP}| + \tfrac12|\mathit{FP}| + \tfrac12|\mathit{FN}|} = \underbrace{\frac{\sum_{(p,g)\in \mathit{TP}}\text{IoU}(p,g)}{|\mathit{TP}|}}_{\text{SQ}} \times \underbrace{\frac{|\mathit{TP}|}{|\mathit{TP}| + \tfrac12|\mathit{FP}| + \tfrac12|\mathit{FN}|}}_{\text{RQ}}.

A match requires IoU>0.5\text{IoU} > 0.5. PQ is computed per class, then averaged over classes with at least one true-positive, false-positive, or false-negative segment. Segmentation quality (SQ) is the average IoU of the matched pairs. Recognition quality (RQ) is an F1-like term that penalizes missed and extra segments. The factorization follows by multiplying and dividing by ∣TP∣|\mathit{TP}| when at least one match exists. If ∣TP∣=0|\mathit{TP}| = 0 but the denominator is nonzero, PQ is 00 and the factorization is not used.

Lemma (matches are unique). If predicted segments and ground-truth segments are each pairwise disjoint, as the panoptic format requires, then IoU>0.5\text{IoU} > 0.5 pairs one-to-one. Each segment can match at most one segment from the other set.

Proof. Suppose a prediction pp has IoU(p,g)>12\text{IoU}(p, g) > \tfrac12. Then

∣p∩g∣>12 ∣p∪g∣definition of IoU, rearranged≥12 ∣g∣since g⊆p∪g.\begin{aligned} |p \cap g| &> \tfrac12\,|p \cup g| && \text{definition of IoU, rearranged}\\[2pt] &\ge \tfrac12\,|g| && \text{since } g \subseteq p \cup g. \end{aligned}

So every matching prediction covers more than half of gg. Now suppose two predictions p1,p2p_1, p_2 both matched gg. The panoptic format keeps predictions disjoint, so p1∩gp_1 \cap g and p2∩gp_2 \cap g are disjoint subsets of gg, each larger than 12∣g∣\tfrac12|g|. Together they would hold more than ∣g∣|g| pixels inside gg, which is impossible. So at most one prediction matches gg. The same argument runs the other way. Since the panoptic format also keeps the ground-truth segments disjoint, and p⊆p∪gp \subseteq p \cup g gives ∣p∩g∣>12∣p∣|p \cap g| > \tfrac12|p|, each prediction matches at most one ground truth. ■\blacksquare

Above the 0.50.5 threshold, matching is therefore unambiguous. Greedy matching, which pairs segments one at a time with the best still-unclaimed partner, is exact.

2. Mask classification: predict regions, not pixels

A model can produce a segmentation in two ways. It can label every pixel, or it can predict a set of regions and label each region. Mask2Former does the second.

Labeling pixels. A per-pixel classifier asks the same question at every pixel: which class is this? The fully convolutional network (FCN) [Long et al. 2015] made this the standard approach to semantic segmentation. It is trained with cross-entropy at every pixel, the negative log of the probability it gives the correct class.

The catch is object identity. A per-pixel classifier has no variable for which object a pixel belongs to, so it cannot separate two touching cars. Instance systems added extra machinery for that: region proposals, anchor boxes, grouping rules, or non-maximum suppression (NMS), a step that deletes overlapping duplicate detections.

Predicting regions. Mask classification predicts regions instead. The model keeps NN learned query vectors. Each query predicts one mask, which says where its segment is, and one class, which says what the segment is:

{(mi,ci)}i=1N,mi∈[0,1]H×W,ci∈{1,…,K}∪{∅},\{(m_i, c_i)\}_{i=1}^{N}, \qquad m_i \in [0,1]^{H\times W},\quad c_i \in \{1,\dots,K\}\cup\{\varnothing\},

where the mask mim_i gives every pixel a probability of belonging to segment ii, KK is the number of classes, and ∅\varnothing is an extra “no object” class for queries that find nothing. The mask and the class come from the same query, so they describe the same segment. Object identity comes for free, because two cars are two queries. The design comes from DETR [Carion et al. 2020], a detector built on learned queries, by way of MaskFormer [Cheng et al. 2021], Mask2Former’s direct predecessor.

Where mask classification comes from

Mask R-CNN [He et al. 2017] predicts a binary mask inside each detected box. DETR [Carion et al. 2020] replaced hand-built proposals with learned queries and one-to-one matching, and its panoptic extension decoded masks from those queries. MaX-DeepLab [Wang et al. 2021] brought end-to-end set prediction to panoptic segmentation. MaskFormer [Cheng et al. 2021] showed that the same prediction format could outperform per-pixel models on semantic segmentation. K-Net [Zhang et al. 2021] pursued a related design with one dynamic convolution kernel per segment.

Fig. 2 shows one such query on a real photo.

A photograph of a French bulldog with its predicted mask in gold, and beside it the soft mask, gold where the probability is high, with its 0.5 level outlined.
Fig. 2. One query predicts one region and its class. This is the dog query of the trained model, the released Swin-L checkpoint. Right, its mask as probabilities, white at 0 and gold at 1, with the 0.5 level in black. Left, the mask thresholded at 0.5. The query says dog with probability 0.999.

The same format covers all three tasks. Semantic targets contain one mask per class present in the image, instance targets one mask per object, and panoptic targets one mask per thing or stuff segment.

Mask2Former’s thesis is that this format was right, and that MaskFormer’s decoder and training recipe held it back.

3. How a query becomes a mask

Mask2Former keeps MaskFormer’s three parts, drawn in the overview figure at the top. Each part hands its output to the next.

  1. A backbone, either a ResNet [He et al. 2016] or a Swin Transformer [Liu et al. 2021], turns the image into feature maps.
  2. A pixel decoder refines them into feature maps at three resolutions, 1/32, 1/16 and 1/8 of the input. It also produces a pixel embedding map Epixel\mathcal{E}_{\text{pixel}} at 1/4 resolution, with one vector of C=256C = 256 numbers per location.
  3. A Transformer decoder updates the NN query vectors in nine layers, each reading one of the three feature maps (§5, §6).

After every decoder layer, two small heads read each query’s vector qiq_i. The class head is a linear layer with a softmax, which gives one probability per class plus one for no-object. The mask head is a small multilayer perceptron (MLP) that turns the query into a mask embedding, a vector the same length as each pixel embedding. The mask is the sigmoid of their dot product at every pixel xx:

mi(x)=σ(MLP⁡(qi)⊤ Epixel(x)),m_i(x) = \sigma\big(\operatorname{MLP}(q_i)^\top\, \mathcal{E}_{\text{pixel}}(x)\big),

where σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}) turns the dot product, called the mask logit, into a probability. A pixel whose embedding points the same way as the query’s mask embedding gets a high probability. Every part, from the backbone to the heads, is trained together on the loss of §4, so the pixels of an object learn embeddings that line up with its query. Fig. 3 shows this on the real model.

Fig. 3. A mask is one dot product per pixel. Each dot is one pixel of the trained model's embedding map. Across is how far the pixel's embedding points along the dog query's vector, and height only spreads the dots out. On the dashed line the dot product is 0, which the sigmoid turns into probability 0.5, and the pixels to its right form the mask. The animation places 260 sample pixels, drawn as cells on the photo, then applies the same rule to all 60,800.

Masks are computed at 1/4 of the input resolution, 256 by 256 for a 1024 by 1024 image, and then upsampled. Because the heads run after every layer, each query makes ten predictions: one from the learnable initial queries and one after each of the nine layers. Training supervises all ten (§4.2), and each of the first nine also decides where the next layer may look (§5).

From predictions to the output. At inference, the final NN predictions become the answer each task needs. Panoptic output gives each pixel to the confident query with the highest class probability times mask probability. Instance output ranks every query and class pair by its probability and keeps the top 100 as detections. Semantic output weights each mask by its class probabilities and labels every pixel with the class that collects the most weight. The exact rules are folded below.

How the outputs are post-processed

Panoptic output first keeps queries whose best class is not no-object and whose class probability exceeds 0.80.8. Each pixel chooses the kept query with the largest class-probability times mask-probability score. The pixel is written only if the winning query’s mask probability is at least 0.50.5. For each query, the code divides the number of pixels it wins by the number of pixels in its own thresholded mask and discards the segment when this ratio is below 0.80.8. The final segment is the intersection of the winning pixels and that thresholded mask. Stuff segments with the same class are merged. Rejected pixels remain void.

Semantic output drops the no-object column and labels each pixel xx with arg⁡max⁡c∑ip^i(c) mi(x)\arg\max_c \sum_i \hat p_i(c)\, m_i(x). Both of these rules come from MaskFormer.

Instance output flattens the N×KN\times K query-class probabilities and selects the highest-scoring pairs. The released code keeps the top 100 pairs per image. The same query mask can therefore appear with more than one class before the top-pair cutoff. For a selected pair (i,c)(i,c), the final score multiplies its class probability by the average mask probability over the predicted foreground.

si,c=p^i(c) ∑xmi(x) 1[mi(x)>0.5]∑x1[mi(x)>0.5]+ε.s_{i,c} = \hat p_i(c)\, \frac{\sum_x m_i(x)\,\mathbb{1}[m_i(x)>0.5]} {\sum_x \mathbb{1}[m_i(x)>0.5] + \varepsilon}.

The implementation uses ε=10−6\varepsilon = 10^{-6}, so an empty foreground scores zero. This mask-weighted score is Mask2Former’s addition.

4. Training: one query per object

Training has to decide which query should predict which object, and nothing in the output says so. The NN predictions form a set. Query 7 is not meant to predict object 7, and shuffling the queries only reorders the same predictions. So the loss works in two steps: matching pairs each real object with one query, and the loss then scores each pair. Mask2Former inherits this from DETR and MaskFormer. If you know DETR’s matching, skip to the last paragraph of §4.2, on deep supervision.

4.1 Matching predictions to objects

Letting each prediction pick the target it fits best does not work: two queries can pick the same object and leave another with none. Matching instead gives each target exactly one prediction, choosing the pairing with the lowest total cost. Every prediction left over learns to say no-object. That includes a second query on an object that is already taken, so the model learns not to predict duplicates, and inference needs no non-maximum suppression.

Try a small case first. Fig. 4 holds the costs of pairing three predictions with three targets. Before it plays, find the cheapest way to give each target its own prediction.

Fig. 4. Matching is a global choice. Each entry is the cost of giving a target (column) to a prediction (row), lower when the prediction's class and mask fit the target better. Taking the cheapest pair first locks in the 0 and the 2 and is left with a 4, for a total of 6. The best assignment accepts one slightly worse pair and pays 5 in total. The Hungarian algorithm finds it.

The cost. In the model, the cost of pairing prediction ii with target jj has three parts. A class term rewards a prediction that already gives the target’s class cjgtc^{\text{gt}}_j a high probability. Two mask terms measure how far the predicted mask mim_i is from the target mask mjgtm^{\text{gt}}_j: binary cross-entropy (BCE), which scores each pixel on its own, and Dice, which scores the overlap of the whole region (both in §4.2). In full,

cost(i,j)=1 ⁣[cjgt≠∅]( ⁣−λcls p^i(cjgt)+λce Lce(mi,mjgt)+λdice Ldice(mi,mjgt)),\text{cost}(i,j) = \mathbb{1}\!\left[c^{\text{gt}}_j \ne \varnothing\right]\Big(\!-\lambda_{\text{cls}}\,\hat p_{i}(c^{\text{gt}}_j) + \lambda_{\text{ce}}\,\mathcal{L}_{\text{ce}}\big(m_{i}, m^{\text{gt}}_j\big) + \lambda_{\text{dice}}\,\mathcal{L}_{\text{dice}}\big(m_{i}, m^{\text{gt}}_j\big)\Big),

where the indicator 1[⋅]\mathbb{1}[\cdot] is 1 when its condition holds and 0 otherwise, so pairing a query with no object costs nothing. The weights λcls\lambda_{\text{cls}}, λce\lambda_{\text{ce}} and λdice\lambda_{\text{dice}} are 2, 5 and 5, and the minus sign makes a confident correct class lower the cost.

The assignment. With 100 queries there are far too many pairings to try them all. The Hungarian algorithm [Kuhn 1955, Munkres 1957] finds the cheapest one directly, in O(N3)O(N^3) time in its refined form. In code it is one call to scipy.optimize.linear_sum_assignment. The two folds below show why its answer is optimal and run it by hand on the matrix of Fig. 4.

The dual certificate for optimality

Assume an image holds at most NN objects, and fill the target list up to NN with no-object entries ∅\varnothing. Then every query gets exactly one target. An assignment is a permutation π∈SN\pi \in S_N, where SNS_N is the set of all N!N! reorderings and π(j)\pi(j) is the prediction given to target jj. Its total cost is

J(π)=∑j=1Ncost(π(j), j),J(\pi) = \sum_{j=1}^{N} \text{cost}(\pi(j),\, j),

and the matcher picks π^=arg⁡min⁡πJ(π)\hat\pi = \arg\min_{\pi} J(\pi).

The assignment minimization has a companion maximization, its dual, whose value never exceeds the original minimum. The dual attaches a potential to each row, uiu_i, and to each column, vjv_j,

max⁡u,v∈RN ∑iui+∑jvjs.t.ui+vj≤cost(i,j) (∀i,j),\max_{u,v\in\mathbb{R}^N}\ \sum_i u_i + \sum_j v_j \quad\text{s.t.}\quad u_i + v_j \le \text{cost}(i,j)\ (\forall i,j),

and dual feasibility is exactly the reduced cost c~(i,j)=cost(i,j)−ui−vj\tilde c(i,j) = \text{cost}(i,j) - u_i - v_j staying nonnegative everywhere.

The optimality certificate. Take any row potentials u1,…,uNu_1,\dots,u_N and column potentials v1,…,vNv_1,\dots,v_N, and sum the reduced costs along an assignment π\pi:

∑j=1Nc~(π(j), j)=∑j=1N[cost(π(j), j)−uπ(j)−vj]definition of c~=∑j=1Ncost(π(j), j)−∑j=1Nuπ(j)−∑j=1Nvjsplit the sum=J(π)−∑i=1Nui−∑j=1Nvjreindex the u sum.\begin{aligned} \sum_{j=1}^{N} \tilde c(\pi(j),\, j) &= \sum_{j=1}^{N}\big[\text{cost}(\pi(j),\, j) - u_{\pi(j)} - v_j\big] && \text{definition of } \tilde c\\[2pt] &= \sum_{j=1}^{N}\text{cost}(\pi(j),\, j) - \sum_{j=1}^{N} u_{\pi(j)} - \sum_{j=1}^{N} v_j && \text{split the sum}\\[2pt] &= J(\pi) - \sum_{i=1}^{N} u_i - \sum_{j=1}^{N} v_j && \text{reindex the } u \text{ sum}. \end{aligned}

The reindexing is legitimate because π\pi is a permutation. The map j↦π(j)j \mapsto \pi(j) hits every row index once, so ∑juπ(j)=∑iui\sum_j u_{\pi(j)} = \sum_i u_i. The two potential sums do not depend on π\pi, so the potentials shift every assignment’s total by the same constant, and arg⁡min⁡π\arg\min_\pi is unchanged. Call the potentials feasible when c~(i,j)≥0\tilde c(i,j) \ge 0 everywhere, and an edge tight when c~(i,j)=0\tilde c(i,j) = 0.

Lemma (a tight assignment is optimal). If feasible potentials admit an assignment π\pi that uses only tight edges, then π\pi minimizes JJ.

Proof. Let π′\pi' be any assignment. Rearranging the certificate identity,

J(π′)=∑j=1Nc~(π′(j), j)+∑i=1Nui+∑j=1Nvjthe identity above≥∑i=1Nui+∑j=1Nvjsince every c~≥0.\begin{aligned} J(\pi') &= \sum_{j=1}^{N} \tilde c(\pi'(j),\, j) + \sum_{i=1}^{N} u_i + \sum_{j=1}^{N} v_j && \text{the identity above}\\[2pt] &\ge \sum_{i=1}^{N} u_i + \sum_{j=1}^{N} v_j && \text{since every } \tilde c \ge 0. \end{aligned}

So ∑iui+∑jvj\sum_i u_i + \sum_j v_j lower-bounds the cost of every assignment. The tight π\pi uses only edges with c~(π(j), j)=0\tilde c(\pi(j),\, j) = 0, so its first sum vanishes and J(π)=∑iui+∑jvjJ(\pi) = \sum_i u_i + \sum_j v_j. That equals the lower bound, so no assignment costs less. ■\blacksquare

This equality is complementary slackness. With respect to an optimal dual solution, an optimal assignment uses only edges with c~=0\tilde c=0.

A worked 3×3 Hungarian run and the O(N³) bound

The primal-dual algorithm. Instead of checking all N!N! assignments, the Hungarian method grows a matching while keeping matched edges tight and every reduced cost nonnegative. Consider three predictions against three targets, with prediction ii in row ii, target jj in column jj, and the costs collected in a matrix written CC for this example only.

C=(413205322).C = \begin{pmatrix} 4 & 1 & 3\\ 2 & 0 & 5\\ 3 & 2 & 2 \end{pmatrix}.

Make zeros. Start with u=v=0u = v = 0. Row and column reductions create enough zero reduced costs to begin matching. Subtract each row’s minimum from its row, which sets ui=min⁡jcost(i,j)u_i = \min_j \text{cost}(i,j), then subtract each remaining column minimum, vj=min⁡ic~(i,j)v_j = \min_i \tilde c(i,j). The certificate identity makes this legal because the potentials shift every assignment by the same constant. Here u=(1,0,2)u = (1, 0, 2) and then v=(1,0,0)v = (1, 0, 0).

c~=C−u−v=(202105000).\tilde c = C - u - v = \begin{pmatrix} 2 & 0 & 2\\ 1 & 0 & 5\\ 0 & 0 & 0 \end{pmatrix}.

Every row and every column now holds a zero. The column pass cannot remove a row’s zero because that zero sits in a column whose minimum is already 00, so vj=0v_j=0 there and the entry stays unchanged.

Match on zeros. Pair rows to columns through tight edges only, never reusing a row or a column. Row 1 takes column 2 and row 3 takes column 1. Row 2’s only zero sits in column 2, already taken, so the matching stalls at two pairs.

The tool for getting unstuck is the augmenting path. Call a row or column free while it has no partner. An augmenting path starts at a free row and steps to a column through a zero. From that column it follows the matched edge to the partner row, then steps to a new column through another zero. It keeps alternating until it lands on a free column. Flip every edge along it, so matched edges become unmatched and unmatched edges become matched. Each interior row and column trades one partner for another while the two free endpoints gain one, so the matching grows by exactly one pair. Matching as far as possible means flipping augmenting paths until none exists.

None exists here. From the free row 2 the only zero leads to column 2, column 2’s partner is row 1, and row 1 owns no other zero to continue through.

Create a new zero. The rows and columns just visited form the alternating tree, here rows I={2,1}I = \{2, 1\} and columns J={2}J = \{2\}. These names are local to this example. Progress needs a zero on an edge from a row in II to a column outside JJ. Take the smallest remaining reduced cost on such an edge.

δ=min⁡i∈I, j∉Jc~(i,j)=c~(2,1)=1,\delta = \min_{i\in I,\ j\notin J}\tilde c(i,j) = \tilde c(2,1) = 1,

and pay for it with the potentials. Raise uiu_i by δ\delta on every tree row and lower vjv_j by δ\delta on every tree column. Call this move a lift. Three checks, one per kind of entry, show it is safe.

  • Tree row, outside column. The reduced cost drops by δ\delta. By the choice of δ\delta nothing goes negative, and the minimizer lands exactly on zero. That is the purchased edge, (2,1)(2,1) here.
  • Tree row, tree column. The raise and the drop cancel, so every edge inside the tree, the matched ones included, stays exactly as tight as it was.
  • Outside row, tree column. The reduced cost rises by δ\delta, harmless for nonnegativity, and the only zeros this can erase are unmatched ones, because a tree column’s partner sits inside the tree.

So the invariants hold and the tree gains ground. The dual objective ∑iui+∑jvj\sum_i u_i + \sum_j v_j also rises by δ\delta, because the tree always holds one more row than column. Every column it reaches is matched, since a free column would already end an augmenting path. Each matched column brings its partner row along, so only the root row lacks a column. The lower bound climbs toward the optimum with every lift. With u=(2,1,2)u = (2, 1, 2) and v=(1,−1,0)v = (1, -1, 0),

c~=(101004010).\tilde c = \begin{pmatrix} 1 & 0 & 1\\ 0 & 0 & 4\\ 0 & 1 & 0 \end{pmatrix}.

Augment. The purchased zero at (2,1)(2,1) extends the search. Row 2 now reaches column 1, column 1’s partner row 3 joins, and row 3 owns a zero in column 3, which is free. That is an augmenting path, row 2 to column 1 to row 3 to column 3. Flip it. Row 2 takes column 1, row 3 moves to column 3, row 1 keeps column 2, and the matching is perfect.

Read off the certificate. In the original matrix the assignment costs C12+C21+C33=1+2+2=5C_{12} + C_{21} + C_{33} = 1 + 2 + 2 = 5, and the potentials sum to (2+1+2)+(1−1+0)=5(2 + 1 + 2) + (1 - 1 + 0) = 5. Primal equals dual, so by the lemma no assignment can cost less. The potentials are an optimal dual solution, and the equality that just closed is complementary slackness checked by hand. In general, match through zeros until stuck, buy the cheapest escape zero, augment the moment a free column comes into reach, and stop when every row has a partner.

Each augmentation adds one edge, so at most NN augmentations finish the matching. One piece of bookkeeping makes each augmentation cost O(N2)O(N^2). For every column outside the tree, keep its current slack min⁡i∈Ic~(i,j)\min_{i\in I}\tilde c(i,j) and update it in O(N)O(N) when a row joins. Each δ\delta is then read from the slacks rather than found by rescanning the matrix. Every lift either reaches a free column and enables an augmentation, or adds a matched column and its partner row to the tree. Thus at most NN lifts occur between augmentations, giving O(N3)O(N^3) work overall. The Jonker-Volgenant routine called by scipy is a faster-constant refinement of the same primal-dual idea.

4.2 The training loss

Each output is trained with three terms: a class loss on all NN queries, and two mask losses on the queries matched to real objects. The loss weights them as

L=2 Lcls+5 Lce+5 Ldice.\mathcal{L} = 2\,\mathcal{L}_{\text{cls}} + 5\,\mathcal{L}_{\text{ce}} + 5\,\mathcal{L}_{\text{dice}}.

The class loss Lcls\mathcal{L}_{\text{cls}} is cross-entropy, with no-object targets weighted 0.1, because most queries are unmatched: with 100 queries and 5 objects, 95 learn no-object. BCE, Lce\mathcal{L}_{\text{ce}}, scores each mask point on its own and keeps pushing a point that is confidently wrong. Dice, Ldice\mathcal{L}_{\text{dice}} [Milletari et al. 2016], scores the overlap of the whole region, from 0 for a perfect match to almost 1 for none, so a small object counts as much as a large one at the same fraction of overlap. Its push on a confidently wrong point fades, which is why BCE is kept beside it. Both are evaluated at sampled points (§6.2).

The loss formulas, their gradients, and what BCE adds to Dice

Class loss. After matching, write yiy_i for the class that query ii should predict: its target’s class if it was matched, and ∅\varnothing if not. For one image, the class loss is a weighted cross-entropy over the query slots,

Lcls=∑i=1Nw(yi)[−log⁡p^i(yi)]∑i=1Nw(yi),w(yi)={1yi≠∅,0.1yi=∅.\mathcal{L}_{\text{cls}} = \frac{\sum_{i=1}^{N} w(y_i)\big[-\log \hat p_i(y_i)\big]} {\sum_{i=1}^{N} w(y_i)}, \qquad w(y_i) = \begin{cases} 1 & y_i \ne \varnothing,\\ 0.1 & y_i = \varnothing. \end{cases}

Mask2Former inherits the 0.10.1 weight from DETR. The paper’s text states it as λcls=2.0\lambda_{\text{cls}} = 2.0 for matched predictions and 0.10.1 for no-object. The released code applies the 0.10.1 inside this weighted mean, which is then scaled by 22.

BCE. At a point xx with mask logit zxz_x, prediction mx=σ(zx)m_x = \sigma(z_x), and target gx∈{0,1}g_x \in \{0,1\}, it is

ℓce(x)=−[gxlog⁡σ(zx)+(1−gx)log⁡(1−σ(zx))].\ell_{\text{ce}}(x) = -\big[g_x \log \sigma(z_x) + (1-g_x)\log\big(1-\sigma(z_x)\big)\big].

Its gradient with respect to the logit is simply

∂ℓce∂zx=σ(zx)−gx,\frac{\partial \ell_{\text{ce}}}{\partial z_x} = \sigma(z_x) - g_x,

so every point is pushed toward its target, and a confidently wrong point gets close to the largest push, of size 1.

Dice. Write O=∑xmxgxO = \sum_x m_xg_x for the overlap and S=∑xmx+∑xgxS = \sum_xm_x + \sum_xg_x for the size sum. The released implementation computes

Ldice(m,g)=1−2O+1S+1,\mathcal{L}_{\text{dice}}(m,g) = 1 - \frac{2O+1}{S+1},

where the added 1s keep the ratio defined when both masks are empty.

BCE in the released code. The same gradient holds for bilinearly sampled targets gx∈[0,1]g_x \in [0,1]. The released loss averages BCE over sampled points and normalizes by the number of matched masks. BCE has no mask-level normalization for foreground area. Under dense evaluation, or uniform sampling in expectation, a large foreground contributes more positive terms than a small one at comparable pointwise errors. The training sampler in §6.2 can change those proportions by favoring logits near zero.

Dice’s gradient. Milletari’s original Dice uses sums of squares in the denominator. Dice couples all sampled points through one region-level score. Write the smoothing constant as ε=1\varepsilon = 1. The gradient at a single point is

∂Ldice∂mx=− 2 gx (S+ε)−(2O+ε)(S+ε)2.\frac{\partial \mathcal{L}_{\text{dice}}}{\partial m_x} = -\,\frac{2\,g_x\,(S+\varepsilon) - (2O+\varepsilon)}{(S+\varepsilon)^2}.

To derive it, differentiate with respect to the single probability mxm_x. Every other term of each sum is constant, so

∂O∂mx=gx,∂S∂mx=1.\frac{\partial O}{\partial m_x} = g_x, \qquad \frac{\partial S}{\partial m_x} = 1.

Then, using the quotient rule in the form (u/v)′=(u′v−uv′)/v2(u/v)' = (u'v - uv')/v^2,

∂Ldice∂mx=− ∂∂mx ⁣(2O+εS+ε)drop the constant 1=− 2 (∂O/∂mx) (S+ε)−(2O+ε) (∂S/∂mx)(S+ε)2quotient rule=− 2 gx (S+ε)−(2O+ε)(S+ε)2insert the partials.\begin{aligned} \frac{\partial \mathcal{L}_{\text{dice}}}{\partial m_x} &= -\,\frac{\partial}{\partial m_x}\!\left(\frac{2O+\varepsilon}{S+\varepsilon}\right) && \text{drop the constant } 1\\[4pt] &= -\,\frac{2\,(\partial O/\partial m_x)\,(S+\varepsilon) - (2O+\varepsilon)\,(\partial S/\partial m_x)}{(S+\varepsilon)^2} && \text{quotient rule}\\[4pt] &= -\,\frac{2\,g_x\,(S+\varepsilon) - (2O+\varepsilon)}{(S+\varepsilon)^2} && \text{insert the partials}. \end{aligned}

How Dice scales with area. When S>0S>0, the unsmoothed form gives an exact view of area scaling. Tile kk disjoint copies of the same prediction and target pattern. Then OO becomes kOkO and SS becomes kSkS, so the Dice value is unchanged. In the derivative above with ε=0\varepsilon=0, the numerator grows by a factor of kk while the denominator grows by a factor of k2k^2. Each copied point therefore receives 1/k1/k of the original derivative. If both masks are empty, the unsmoothed ratio is undefined, which is one reason the implementation adds 11. This area normalization does not make the BCE component scale-invariant.

What BCE adds to Dice. Dice has a weakness one step further back, in logit space. When the prediction confidently misses the target, mxm_x is near 0 where gx=1g_x = 1. The chain rule then multiplies ∂Ldice/∂mx\partial\mathcal{L}_{\text{dice}}/\partial m_x by σ′(zx)≈0\sigma'(z_x) \approx 0, so the gradient vanishes through the saturated sigmoid. BCE cancels that factor exactly, as its logit gradient σ(zx)−gx\sigma(z_x) - g_x shows. BCE therefore supplies a direct logit gradient at every point, while Dice adds region-normalized overlap.

Why not focal loss, as in MaskFormer?

MaskFormer used focal loss [Lin et al. 2017] with weight 2020. Focal loss down-weights already-confident predictions, so easy background points contribute less. Mask2Former uses plain BCE at weight 55. One plausible reason is that the training sampler of §6.2 spends most of its budget on uncertain locations rather than easy background, reducing the imbalance that focal loss was designed to address. The paper does not isolate this change.

Deep supervision. All ten outputs of §3 are trained with this loss, through the same shared heads. The matching is recomputed for each output, so every intermediate prediction trains toward its own assignment. This matters more than usual here: the intermediate masks become the attention masks of §5, so these losses also steer where each layer looks.

5. Masked attention: each query reads only its own region

In a standard decoder layer, every query reads the whole image through cross-attention. A query meant to describe the dog still spends attention on every patch of blanket. Global attention can learn where an object is, but the authors argue that learning this is slow, as earlier DETR studies had found [Gao et al. 2021, Sun et al. 2021]. Masked attention removes the problem by construction: each query reads only inside the mask it predicted at the previous layer.

5.1 Why global attention spreads thin

A small calculation shows how the background wins. Suppose the object covers 2 percent of the image, and every object location scores 2 higher than every background location. There are 49 background locations for each object location, and each of them gets e−2≈0.135e^{-2} \approx 0.135 of an object location’s weight. The object’s share of the attention is then only

11+49 e−2≈11+49⋅0.135=17.615≈0.13.\frac{1}{1 + 49\,e^{-2}} \approx \frac{1}{1 + 49 \cdot 0.135} = \frac{1}{7.615} \approx 0.13.

The background wins by numbers, not by score. Real scores vary, so this is only a toy, but it shows why reading only the object’s region can make learning easier.

5.2 The masked update

Masked attention keeps the attention step of Fig. 0 and adds one term to the scores. Before reading on, take the four locations of Fig. 0 and suppose the previous mask keeps locations 1 and 4. What should happen to the weights of locations 2 and 3, and to the other two? Fig. 5 plays it out.

Fig. 5. Masked attention zeroes the weights outside the previous mask and rescales the rest. A location's score says how well it matches the query, its weight is exp(score) divided by the sum over locations, and the output mixes the locations' vectors v by weight. The scores are made up. The mask is the model's real dog mask, which keeps locations 1 and 4. The other two get score −∞ and weight 0, so the kept weights grow to 0.71 and 0.29.

The gain is small here because locations 2 and 3 held little weight. In the toy image of §5.1, where the background held 87 percent of the attention, a gate that keeps only the object lifts the object’s share from 0.13 to 1.

In symbols, masked attention adds a mask M\mathcal{M} to the scores before the softmax. For query ii, with the softmax taken over image locations xx,

weighti(x)=softmax⁡x ⁣(scorei(x)+Mi(x)),Mi(x)={0inside query i’s previous mask,−∞outside it.\text{weight}_i(x) = \operatorname{softmax}_x\!\big(\text{score}_i(x) + \mathcal{M}_i(x)\big), \qquad \mathcal{M}_i(x) = \begin{cases} 0 & \text{inside query } i\text{'s previous mask},\\ -\infty & \text{outside it}. \end{cases}

The previous mask is the one the query predicted at the layer before, resized to the feature map this layer reads and thresholded at probability 0.5. The first layer uses the mask predicted from the learned starting queries (§7). Self-attention, the next step in the layer, still carries information between queries, so a query that reads only its own region can still learn from the others.

The paper's equations

The paper writes the standard cross-attention step of layer ll as

X~l=softmax⁡ ⁣(QlKl⊤) Vl+Xl−1,(1)\widetilde{\mathbf{X}}_l = \operatorname{softmax}\!\big(\mathbf{Q}_l \mathbf{K}_l^{\top}\big)\,\mathbf{V}_l + \mathbf{X}_{l-1}, \tag{1}

where Ql\mathbf{Q}_l comes from the queries after the previous layer, Xl−1\mathbf{X}_{l-1}, and Kl\mathbf{K}_l and Vl\mathbf{V}_l come from the image features that layer ll reads. X~l\widetilde{\mathbf{X}}_l is the queries’ state right after this step. Self-attention and the feed-forward network then turn it into the layer’s output Xl\mathbf{X}_l. The equation leaves out LayerNorm, the 1/d1/\sqrt d scaling, the heads and the positional embeddings of §7.

Masked attention adds the mask Ml−1\mathcal{M}_{l-1} to the scores before the softmax:

X~l=softmax⁡ ⁣(Ml−1+QlKl⊤) Vl+Xl−1,(2)\widetilde{\mathbf{X}}_l = \operatorname{softmax}\!\big(\mathcal{M}_{l-1} + \mathbf{Q}_l \mathbf{K}_l^{\top}\big)\,\mathbf{V}_l + \mathbf{X}_{l-1}, \tag{2} Bl−1(i,x)=1 ⁣[σ ⁣(resize⁡(Zl−1)i(x))≥0.5],Ml−1(i,x)={0if Bl−1(i,x)=1,−∞otherwise,(3)\begin{aligned} B_{l-1}(i,x) &= \mathbb{1}\!\left[\sigma\!\left(\operatorname{resize}(Z_{l-1})_i(x)\right) \ge 0.5\right],\\[4pt] \mathcal{M}_{l-1}(i,x) &= \begin{cases} 0 & \text{if } B_{l-1}(i,x) = 1,\\[2pt] -\infty & \text{otherwise,} \end{cases} \end{aligned} \tag{3}

where Zl−1Z_{l-1} holds the previous output’s mask logits, one map per query. Each query’s logits are bilinearly resized to the resolution of the map that layer ll reads, then passed through the sigmoid σ\sigma and thresholded at 0.50.5. The result is the gate Bl−1B_{l-1}, which is 1 where the query may look. The first layer uses Z0Z_0, predicted directly from the learnable queries (§7).

Does it help? The paper swaps out one part at a time to find out. With a ResNet-50 (R50) backbone on COCO, plain cross-attention reaches 37.8 AP and masked attention 43.7. Even mask pooling, which simply averages the features inside the mask, reaches 43.1. So on COCO, most of the gain comes from limiting where a query reads, and masked attention adds a learned weighting inside the region.

The gate is a hard threshold, so no gradient passes through it. The intermediate masks learn from deep supervision instead (§4.2), which compares each intermediate prediction directly with the target mask.

What happens when a mask is empty

If a query’s thresholded mask is empty at some scale, every score in its row would be −∞-\infty and the softmax would be undefined. The code then lets that query read every location for one layer.

attn_mask = (mask_logits.sigmoid() < 0.5).flatten(2)   # True = forbidden
attn_mask[attn_mask.all(dim=-1)] = False               # Fall back to global attention.

Without the guard, the row’s softmax denominator is zero, which can introduce a NaN. The following self-attention mixes information across queries, so that invalid value can contaminate other query states, the loss, and the gradients. Flipping the row to fully unmasked gives the softmax every location to normalize over.

5.3 The effect, measured and seen

The paper also measures how much of each query’s attention lands inside its own object, the true segment it was matched to. With standard cross-attention the share is about 0.20. With masked attention it is 0.59. It stays below 1 partly because the gate is the previous predicted mask, at a coarse resolution, not the true one.

Fig. 6 shows the mechanism in the released Swin-L checkpoint. The query’s class settles early: it says dog with probability 0.98 after layer 2, and at least 0.998 from layer 3 on.

Fig. 6. Each layer reads only inside the previous layer's mask. Each cell shows where the dog query reads in one of the nine decoder layers: rows are layers 1 to 3, 4 to 6 and 7 to 9, and columns the 1/32, 1/16 and 1/8 maps. The outline is the previous layer's mask. Dark gold is the smallest area that holds half of the query's attention, and light gold 90 percent.

6. Making it affordable

Masked attention is the main idea. Two more ideas make it affordable: each layer reads only one feature resolution, and the mask losses are computed on sampled points instead of every pixel.

6.1 One resolution per layer

Small objects need fine feature maps, but attention over a fine map is expensive. Its cost grows with the number of locations. For a 1024 by 1024 input, the 1/32, 1/16 and 1/8 maps hold 1,024, 4,096 and 16,384 locations, so the finest map costs about sixteen times more than the coarsest.

Mask2Former reads one scale per layer. Layers 1, 2 and 3 read the 1/32, 1/16 and 1/8 maps, and the cycle repeats twice more, as Fig. 6 shows on the dog query. This round-robin reaches 43.7 AP at 226 GFLOPs, billions of operations per image. Feeding all three scales to every layer costs 21 more GFLOPs and is no better overall: 0.3 AP higher, the same PQ, and 0.9 mIoU lower.

The pixel decoder builds these maps by letting every location mix in information from all three scales. It uses multi-scale deformable attention (MSDeformAttn) from Deformable DETR [Zhu et al. 2021], in which each location reads a few learned sample points per scale rather than every location.

6.2 Mask losses on 12,544 points

For every output it trains, MaskFormer compared whole masks pixel by pixel twice: once for every prediction-target pair to build the matching costs, and again for the matched pairs to compute the loss. That limited training to one image per 32 GB GPU. Following PointRend [Kirillov et al. 2020], Mask2Former evaluates these terms at only Kpt=12,544=1122K_{\text{pt}} = 12{,}544 = 112^2 sampled points per mask.

Matching uses shared uniform points. One set of random points, spread uniformly, is shared by every prediction and target mask in the image, which makes the cost matrix cheaper to build.

Training uses uncertain points. For each matched mask, the PointRend sampler draws 3Kpt=37,6323K_{\text{pt}} = 37{,}632 uniform candidates [Kirillov et al. 2020]. It keeps the 9,408 where the prediction is least sure, the logits closest to zero, then adds 3,136 fresh uniform points. The uncertainty score depends on the prediction, not the ground truth. It is also relative: the sampler always keeps the least-sure quarter of its candidates, so where the unsure band is thin, it also takes points that are only somewhat unsure. Fig. 7 runs both rules on the dog prediction.

Fig. 7. Matching spreads its points evenly, and training puts most of its points where the prediction is unsure. Both rules run on the dog prediction of Fig. 2, with 400 points per mask instead of 12,544 so they stay visible. Left, matching: 400 uniform points, one set shared by every mask. Right, training: of 1,200 uniform candidates, the 300 with logits closest to zero are kept (gold), then 100 fresh uniform points are added. The gold points follow the predicted outline and the uncertain gift box.
Is a point-sampled loss unbiased?

For a loss that adds up over points, such as BCE, the average over uniform random points is unbiased: averaged over many draws, it equals the full average. Dice is a ratio, so for Dice the evidence is the measured result below. The training points are not an unbiased sample of the dense loss. They deliberately spend the training signal where the prediction is unsure.

Does sampling hurt accuracy? The paper tried each use on its own:

matching ontraining loss onAP (COCO)mIoU (ADE20K)training memory per image (GB)
masksmasks41.045.918
maskspoints41.045.96
pointsmasks43.147.318
pointspoints (default)43.747.26

Rows 1 and 2 show that training on points instead of whole masks cuts memory per image from 18 GB to 6 GB at equal accuracy. Rows 1 and 3 show that matching on points adds 2.1 AP.

7. Smaller changes, and what each part is worth

Three smaller changes to the decoder layer cost no extra computation. Together they improve AP by about 1.4, PQ by 1.1, and mIoU by 0.9.

Masked attention comes first. DETR’s layer starts with self-attention. Mask2Former’s starts with masked attention, so each query has image context before the queries interact.

Query features are learnable and directly supervised. DETR starts every query’s features at zero and tells the queries apart only by a learned vector per query, its positional embedding, added before every attention step. Mask2Former keeps that embedding but also learns the starting features X0\mathbf{X}_0, and supervises their masks before the decoder runs, which gives the first layer a useful gate. Learning X0\mathbf{X}_0 raises mIoU, and supervising it raises AP and PQ. The paper compares these first predictions to region proposals [Ren et al. 2015] that the decoder refines.

Dropout is removed. Dropout randomly zeroes activations during training. Taking it out of the decoder improves AP and PQ.

A new training recipe. On COCO, Mask2Former trains for 50 epochs (passes over the training data) at batch 16, where MaskFormer used 300 at batch 64, with large-scale jittering (random rescaling between 0.1 and 2 times) and the loss weights of §4.2. The full comparison is folded below.

The two training recipes, side by side

Both use the AdamW optimizer [Loshchilov & Hutter 2019]. In the decoder row, SA, CA, and MA abbreviate self-attention, cross-attention, and masked attention.

settingMaskFormerMask2Former
optimizerAdamW, learning rate 10−410^{-4}AdamW, learning rate 10−410^{-4}
weight decay10−410^{-4}0.05
schedule (COCO)300 epochs at batch 6450 epochs at batch 16, lr ×0.1 at 90% and 95% of steps
augmentationstandard scale and cropLSJ (large-scale jittering) [Ghiasi et al. 2021], scale 0.1 to 2.0 with a fixed 102421024^2 crop
mask lossfocal (λ=20\lambda{=}20) + Dice (λ=1\lambda{=}1), denseBCE (λ=5\lambda{=}5) + Dice (λ=5\lambda{=}5) on 12,544 points
λcls\lambda_{\text{cls}}1.02.0
decoder6 layers, SA→CA→FFN, dropout 0.1, stride 32 only, zero-init queries9 layers, MA→SA→FFN, no dropout, strides {32,16,8}×3, learnable supervised queries

What each part is worth. The paper takes each part out of the full model, one at a time, and measures the drop. All of these runs use the R50 backbone.

change (removed or varied)ΔAP (COCO)ΔPQ (COCO)ΔmIoU (ADE20K)
remove masked attention−5.9−4.8−1.7
replace point matching with dense masks*−2.7−1.1−1.3
remove multi-scale high-res features−2.2−1.7−1.1
replace supervised learnable features with zero-init−0.8−0.7−1.8
restore dropout−0.7−0.60.0
standard layer order−0.5−0.3−0.9

*Measured with point-sampled training loss fixed. The full two-by-two comparison is in §6.2.

The effects overlap, so the rows do not add up. Taken out one at a time, the three layer changes cost 2.0 AP in total, but together they are worth 1.4.

The paper also builds Mask2Former from MaskFormer one step at a time on COCO. Retraining MaskFormer with Mask2Former’s recipe raises AP from 34.0 to 37.8. Replacing the decoder raises it to 41.5. Replacing MaskFormer’s feature pyramid network (FPN) pixel decoder [Lin et al. 2017b] with MSDeformAttn reaches 43.7. The steps interact, so these gains depend on the order and are not fixed shares of the total.

8. Results and limitations

8.1 Results

The paper’s largest models use a Swin-L backbone. The COCO models also use 200 queries and train for 100 epochs, twice the default.

task / datasetMask2Former (Swin-L)compared withmargin
Panoptic, COCO val57.8 PQMaskFormer 52.7, K-Net 54.6+5.1 / +3.2
Instance, COCO val50.1 APSwin-HTC++ 49.5+0.6
Semantic, ADE20K val57.7 mIoUBEiT 57.0+0.7 at less than half the parameters

The ADE20K result uses inference at several image sizes and a FaPN pixel decoder [Huang et al. 2021] instead of the default. The COCO results use one size. On COCO’s test set, Mask2Former’s 50.5 AP beats Swin-HTC++ at one size, 50.2, but not at several sizes, 51.1.

With a ResNet-50 backbone, Mask2Former reaches 51.9 PQ after 50 epochs, where MaskFormer reaches 46.5 after 300. MaskFormer’s epochs used batches four times larger, and the paper finds it does about as well in 75 epochs at Mask2Former’s batch of 16. Augmentation and losses differ too, so this is not a controlled test of training speed.

The gain is not just scale. Swin-T Mask2Former reaches 53.2 PQ at 232 GFLOPs, above Swin-L MaskFormer’s 52.7 at 792 GFLOPs.

8.2 Limitations

Universal means one architecture, not one checkpoint. A model trained on panoptic labels usually does slightly worse than the same model trained for one task: 41.7 against 43.7 AP on COCO instances, and 46.1 against 47.2 mIoU on ADE20K. Panoptic training does not yet replace task-specific training.

Small objects remain weaker. On COCO’s validation set, Mask2Former’s AP on small objects, under 32232^2 pixels, is 29.9, below Swin-HTC++ at 31.0, although it leads overall.

It is slower, and the query count depends on the task. Mask2Former runs at 8.6 frames per second against MaskFormer’s 17.6 for the ResNet-50 panoptic models. In the paper’s tests, 100 queries work best for instance and semantic segmentation, while 200 help panoptic segmentation slightly.

9. Conclusion

Mask2Former works because its changes form a feedback loop. Matching assigns one target to each query. Deep supervision trains every intermediate mask. Each mask restricts the next cross-attention step, and point sampling makes this repeated supervision affordable.

Later models build on the same design: Mask2Former for video [Cheng et al. 2021b], OneFormer [Jain et al. 2023], which trains one model for all three tasks, and Mask DINO [Li et al. 2023], which adds DETR-style detection. Mask2Former’s lasting contribution is this query-to-mask refinement loop, more than any one benchmark result.

Appendix A. Implementation notes

The reference implementation is facebookresearch/Mask2Former, built on Detectron2 [Wu et al. 2019]. Hugging Face provides it as Mask2FormerForUniversalSegmentation.

The decoder layer in code, and the code's names for the losses

The reference repository was archived on January 1, 2025. In Hugging Face, Mask2FormerImageProcessor or AutoImageProcessor exposes semantic, instance, and panoptic post-processing methods. The decoder core is shown below in simplified PyTorch-style pseudocode.

def decoder_layer(x, feats_l, size_l, pos_l, lvl_emb, query_pos, prev_mask_logits, pixel_embeddings, num_heads):
    # x: (N,B,C) · feats_l: (H_l*W_l,B,C) · size_l: (H_l,W_l)
    m = F.interpolate(prev_mask_logits, size=size_l, mode="bilinear", align_corners=False)
    attn_mask = (m.sigmoid() < 0.5).flatten(2)  # (B,N,H_l*W_l)
    attn_mask = attn_mask[:, None].repeat(1, num_heads, 1, 1).flatten(0, 1).detach()  # (B*num_heads,N,H_l*W_l)
    attn_mask[attn_mask.all(dim=-1)] = False  # Prevent all-masked softmax.

    # The scale embedding is part of both the key and value memory.
    feats_l = feats_l + lvl_emb
    x = norm1(x + cross_attn(q=with_pos(x, query_pos), k=with_pos(feats_l, pos_l), v=feats_l, attn_mask=attn_mask))
    x = norm2(x + self_attn(q=with_pos(x, query_pos), k=with_pos(x, query_pos), v=x))
    x = norm3(x + ffn(x))

    h = decoder_norm(x).transpose(0, 1)
    cls_logits = class_head(h)
    mask_logits = einsum("bnc,bchw->bnhw", mask_head(h), pixel_embeddings)
    return x, cls_logits, mask_logits

The heads run once on X0\mathbf{X}_0 before the loop and after each of nine decoder layers. The initial prediction supplies Z0Z_0. The final output receives the main loss, and the preceding nine outputs receive auxiliary losses.

Matching calls scipy.optimize.linear_sum_assignment, a modified Jonker-Volgenant algorithm, on the rectangular predictions-by-targets matrix of real targets, which is equivalent to the padded square problem of §4.1. In a minibatch of BB images, the class loss takes its weighted mean over all BNBN query slots.

The code’s names differ from this article’s. The released criterion logs the class loss as loss_ce and the mask BCE, this article’s Lce\mathcal{L}_{\text{ce}}, as loss_mask.

References

  1. Cheng, Misra, Schwing, Kirillov, Girdhar. “Masked-attention Mask Transformer for Universal Image Segmentation.” 2022. arXiv:2112.01527 · Code
  2. Cheng, Schwing, Kirillov. “Per-Pixel Classification is Not All You Need for Semantic Segmentation.” 2021. arXiv:2107.06278
  3. Carion, Massa, Synnaeve, Usunier, Kirillov, Zagoruyko. “End-to-End Object Detection with Transformers.” 2020. arXiv:2005.12872
  4. Kirillov, He, Girshick, Rother, Dollár. “Panoptic Segmentation.” 2019. arXiv:1801.00868
  5. Kirillov, Wu, He, Girshick. “PointRend: Image Segmentation as Rendering.” 2020. arXiv:1912.08193
  6. Zhu, Su, Lu, Li, Wang, Dai. “Deformable DETR: Deformable Transformers for End-to-End Object Detection.” 2021. arXiv:2010.04159
  7. Zhang, Pang, Chen, Loy. “K-Net: Towards Unified Image Segmentation.” 2021. arXiv:2106.14855
  8. Wang, Zhu, Adam, Yuille, Chen. “MaX-DeepLab: End-to-End Panoptic Segmentation with Mask Transformers.” 2021. arXiv:2012.00759
  9. He, Gkioxari, Dollár, Girshick. “Mask R-CNN.” 2017. arXiv:1703.06870
  10. Long, Shelhamer, Darrell. “Fully Convolutional Networks for Semantic Segmentation.” 2015. arXiv:1411.4038
  11. Vaswani et al. “Attention Is All You Need.” 2017. arXiv:1706.03762
  12. Kuhn. “The Hungarian Method for the Assignment Problem.” 1955. doi:10.1002/nav.3800020109
  13. Munkres. “Algorithms for the Assignment and Transportation Problems.” 1957. doi:10.1137/0105003
  14. Milletari, Navab, Ahmadi. “V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation.” 2016. arXiv:1606.04797
  15. Lin, Goyal, Girshick, He, Dollár. “Focal Loss for Dense Object Detection.” 2017. arXiv:1708.02002
  16. Lin, Dollár, Girshick, He, Hariharan, Belongie. “Feature Pyramid Networks for Object Detection.” 2017. arXiv:1612.03144
  17. Gao, Zheng, Wang, Dai, Li. “Fast Convergence of DETR with Spatially Modulated Co-Attention.” 2021. arXiv:2101.07448
  18. Sun, Cao, Yang, Kitani. “Rethinking Transformer-based Set Prediction for Object Detection.” 2021. arXiv:2011.10881
  19. Liu et al. “Swin Transformer: Hierarchical Vision Transformer using Shifted Windows.” 2021. arXiv:2103.14030
  20. He, Zhang, Ren, Sun. “Deep Residual Learning for Image Recognition.” 2016. arXiv:1512.03385
  21. Chen et al. “Hybrid Task Cascade for Instance Segmentation.” 2019. arXiv:1901.07518
  22. Ren, He, Girshick, Sun. “Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks.” 2015. arXiv:1506.01497
  23. Huang, Lu, Cheng, He. “FaPN: Feature-Aligned Pyramid Network for Dense Image Prediction.” 2021. arXiv:2108.07058
  24. Loshchilov, Hutter. “Decoupled Weight Decay Regularization.” 2019. arXiv:1711.05101
  25. Ghiasi et al. “Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation.” 2021. arXiv:2012.07177
  26. Bao, Dong, Wei. “BEiT: BERT Pre-Training of Image Transformers.” 2022. arXiv:2106.08254
  27. Everingham et al. “The PASCAL Visual Object Classes Challenge: A Retrospective.” 2015. doi:10.1007/s11263-014-0733-5
  28. Lin et al. “Microsoft COCO: Common Objects in Context.” 2014. arXiv:1405.0312
  29. Zhou et al. “Scene Parsing through ADE20K Dataset.” 2017. Project page
  30. Cheng et al. “Mask2Former for Video Instance Segmentation.” 2021. arXiv:2112.10764
  31. Jain et al. “OneFormer: One Transformer to Rule Universal Image Segmentation.” 2023. arXiv:2211.06220
  32. Li et al. “Mask DINO: Towards a Unified Transformer-based Framework for Object Detection and Segmentation.” 2023. arXiv:2206.02777
  33. Wu, Kirillov, Massa, Lo, Girshick. “Detectron2.” 2019. Code

Citation

Massih, Peter. “Mask2Former, Dissected.” peteramassih.com, Jul 2026. https://peteramassih.com/writing/mask2former/.

@article{massih2026mask2former,
  title   = {Mask2Former, Dissected},
  author  = {Massih, Peter},
  journal = {peteramassih.com},
  year    = {2026},
  month   = {July},
  url     = {https://peteramassih.com/writing/mask2former/}
}