Image understanding, generation, and 3D reconstruction · Semantic, instance and promptable segmentation · VIS014 · Architecture
Mask2Former
Mask2Former unifies semantic, instance and panoptic segmentation through mask classification. Its distinctive masked attention restricts query processing to predicted regions, connecting object-level queries with dense…
In CodeSplash
Documented in the Academy only. There's no Set up button.
- Availability
- Explained here
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Mask2Former unifies semantic, instance and panoptic segmentation through mask classification. Its distinctive masked attention restricts query processing to predicted regions, connecting object-level queries with dense spatial masks rather than assigning every pixel independently.
Question / hypotheses
Can query-based mask classification solve the selected semantic, instance or panoptic task using masked attention? This is a modeling/evaluation question, not a formal null-hypothesis test.
Architecture / computational structure
A backbone and pixel decoder produce multiscale spatial features. A transformer decoder updates mask queries using predicted-mask-constrained cross-attention; query heads predict classes and masks. Bipartite matching associates predictions with ground-truth masks for training.
Assumptions
The query budget must cover plausible object counts. Early inaccurate masks can restrict useful attention, so implementations need the documented fallback for empty allowed regions. Semantic, instance and panoptic labels require different target/postprocessing definitions.
Formula / computational definition
, with on allowed positions and elsewhere. Query-mask logits are dot products of mask embeddings and pixel features; a matched loss combines class, binary-mask and Dice terms.
Parameters and notation
Notation: Here X_l is the query state, Q_l/K_l/V_l are query/key/value projections and M_l is an additive attention mask. Zero permits a location; negative infinity excludes it. The schematic equation suppresses head, projection and normalization details.
Learned or estimated: Backbone/pixel-decoder weights, learned query vectors, attention/feedforward weights, class predictors and mask embeddings.
Hyperparameters and effects: Query count, decoder layers, feature scales, mask threshold, point-sampling count, matching costs and loss weights. More queries can cover denser scenes but increase cost; sampling and mask thresholds alter small-region learning.
Fitting, fine-tuning, and adaptation
Transfer compatible backbone and pixel-decoder weights, replacing task-dependent class heads and initially training queries/heads with a frozen backbone. Then unfreeze with a smaller backbone rate and the correct matched losses. Validate panoptic assembly thresholds and source-class retention independently; adaptation of semantic labels is not achieved merely by renaming class outputs.
How to use and calibrate
Split by independent image source, scene, subject or capture sequence before augmentation; keep near-duplicate frames and crops in the same split. Use mean IoU for semantic output, mask AP for instances and panoptic quality for panoptic output. Report small-object performance, empty-mask handling and actual query count. Evaluate end-to-end postprocessing, since raw query quality alone does not establish final task quality.
Example application
Build one mask-based image parser for semantic categories and separate object instances. This is a proposed use case, not a claim of validated performance on supplied real data.
Interpretation / pitfalls
Watch out
A training loss, confidence score or attention map is not a p-value or causal explanation. Confidence calibration, annotation quality and distribution-shift performance need separate assessment. A correct component calculation does not validate the full architecture, checkpoint or deployment pipeline.
Python and R code examples
Scope: Mask2Former masked cross-attention, including an explicit all-masked-row fallback; supplied masks and logits replace learned predictions. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.
Full-model route: Python: official Mask2Former. R: native torch custom masked attention and mask heads or bridge. The example tests masked attention support and normalization; it is not a full panoptic model.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — Mask2Former masked cross-attention, including an explicit all-masked-row fallback; supplied masks and logits replace learned predictions. Use the shared setup.
Shared setup for this chapter
import numpy as np
from itertools import permutations
def softmax(x):
x=np.asarray(x,dtype=float)
e=np.exp(x-x.max(axis=-1,keepdims=True))
return e/e.sum(axis=-1,keepdims=True)
def bilinear(a,y,x):
y=float(np.clip(y,0,a.shape[0]-1)); x=float(np.clip(x,0,a.shape[1]-1))
y0=int(np.floor(y)); x0=int(np.floor(x))
y1=min(y0+1,a.shape[0]-1); x1=min(x0+1,a.shape[1]-1)
dy=y-y0; dx=x-x0
return (1-dy)*((1-dx)*a[y0,x0]+dx*a[y0,x1])+dy*((1-dx)*a[y1,x0]+dx*a[y1,x1])
logits=np.array([[.2,.8,-.1,.4],[.3,.1,-.2,.7]])
allow=np.array([[True,False,True,False],[False,False,False,False]])
allow[~allow.any(axis=1)]=True # allow global attention if no pixel is allowed
attn=softmax(np.where(allow,logits,-np.inf))
values=np.array([[1.,0.],[0.,1.],[1.,1.],[.5,.2]])
out=attn@values
assert np.all(attn[~allow]==0) and np.allclose(attn.sum(axis=1),1)
print('masked attention:',attn,'outputs:',out)
Component demo, not a trained model — Mask2Former masked cross-attention, including an explicit all-masked-row fallback; supplied masks and logits replace learned predictions. Use the shared setup.
Shared setup for this chapter
softmax <- function(x) {
if(is.null(dim(x))) {e<-exp(x-max(x)); return(e/sum(e))}
t(apply(x,1,function(v) {e<-exp(v-max(v)); e/sum(e)}))
}
bilinear <- function(a,y,x) {
y<-min(max(y,0),nrow(a)-1); x<-min(max(x,0),ncol(a)-1)
y0<-floor(y); x0<-floor(x); y1<-min(y0+1,nrow(a)-1); x1<-min(x0+1,ncol(a)-1)
dy<-y-y0; dx<-x-x0
(1-dy)*((1-dx)*a[y0+1,x0+1]+dx*a[y0+1,x1+1])+dy*((1-dx)*a[y1+1,x0+1]+dx*a[y1+1,x1+1])
}
logits<-matrix(c(.2,.8,-.1,.4,.3,.1,-.2,.7),2,byrow=TRUE)
allow<-matrix(c(TRUE,FALSE,TRUE,FALSE,FALSE,FALSE,FALSE,FALSE),2,byrow=TRUE)
allow[rowSums(allow)==0,]<-TRUE # fallback if all positions are masked
masked<-logits; masked[!allow]<--Inf; attn<-softmax(masked)
values<-matrix(c(1,0,0,1,1,1,.5,.2),4,byrow=TRUE); out<-attn%*%values
stopifnot(all(attn[!allow]==0),max(abs(rowSums(attn)-1))<1e-12)
print(list(masked_attention=attn,outputs=out))
Sources
- Source 1arxiv.org
- Source 2github.com
From the CodeSplash reference, entry VIS014.