Image understanding, generation, and 3D reconstruction · Semantic, instance and promptable segmentation · VIS013 · Architecture
SegFormer
SegFormer combines a hierarchical vision transformer with a lightweight segmentation decoder. It is useful when multiscale image context and reasonably efficient dense prediction are needed without a heavy decoder;
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
SegFormer combines a hierarchical vision transformer with a lightweight segmentation decoder. It is useful when multiscale image context and reasonably efficient dense prediction are needed without a heavy decoder; the transformer hierarchy differs from a single fixed-resolution patch sequence.
Question / hypotheses
Can hierarchical transformer features and a lightweight multiscale decoder segment the target images efficiently? This is a modeling/evaluation question, not a formal null-hypothesis test.
Architecture / computational structure
Overlapping patch embeddings and transformer stages produce features at several resolutions. Efficient attention reduces key/value resolution, and a Mix-FFN adds local positional information through depthwise convolution. The decoder projects, resizes and concatenates multiscale features before predicting pixel classes.
Assumptions
Dense labels must align with image transformations. A resolution-flexible architecture does not guarantee immunity to scale or aspect-ratio shifts. Small classes, thin structures and unfamiliar textures can remain difficult; pixel accuracy can hide minority-class failure.
Formula / computational definition
, , and . For labeled pixels , minimize , excluding ignored labels; stages and the fusion head are jointly learned.
Parameters and notation
Notation: Here F_l contains spatial features from hierarchy level l, W_l projects channels, Resize aligns spatial resolution, and W_o maps fused channels to classes. P_i,y_i is the probability of the true class at valid pixel i.
Learned or estimated: Overlapping patch kernels, attention projections, depthwise/feedforward blocks, normalization parameters and decoder projections/classifier.
Hyperparameters and effects: Stage widths/depths, attention heads and spatial-reduction ratios, crop size, output resolution, dropout and learning rates. More spatial reduction saves attention cost but can discard small-object information; input size affects effective receptive field and memory.
Fitting, fine-tuning, and adaptation
Initialize the encoder from an appropriately licensed image checkpoint; train a new class head with the encoder initially frozen, then unfreeze later stages at a smaller learning rate. Use identical label remapping and ignore conventions in all splits. Monitor source-class retention, target boundary quality and probability calibration; avoid selecting crop size on the test set.
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. Report mean and per-class IoU, boundary scores, memory and latency at the actual image resolution. Compare with convolutional and transformer baselines under equal pretraining and augmentation. Calibrate confidence on independent labeled target images if confidence drives decisions.
Example application
Segment land-cover categories in large images using a multiscale transformer encoder. 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: SegFormer decoder channel projections and fusion across two supplied resolutions; no overlapping patch embedding or transformer blocks. Use the shared setup. Dependencies: NumPy / base R. Validation: Python executed; R unexecuted.
Full-model route: Python: official SegFormer or a verified segmentation implementation. R: native torch custom hierarchy or a labeled Python bridge. The example illustrates learned channel projection and multiscale fusion, not transformer training.
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 — SegFormer decoder channel projections and fusion across two supplied resolutions; no overlapping patch embedding or transformer blocks. 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])
fine=np.arange(8,dtype=float).reshape(4,2)/8 # four spatial sites, two channels
coarse=np.array([[.2,.5,.8]]) # one site, three channels
w_f=np.array([[1.,.2],[.3,.8]]); w_c=np.array([[.2,.1],[.5,.4],[.3,.7]])
projected_f=fine@w_f; projected_c=np.repeat(coarse@w_c,4,axis=0)
fused=np.concatenate([projected_f,projected_c],axis=1)
class_prob=softmax(fused@np.array([[1.,-1.],[.2,.3],[.4,-.2],[-.1,.2]]))
assert fused.shape==(4,4) and np.allclose(class_prob.sum(axis=1),1)
print('fused features:',fused,'two-class probabilities:',class_prob)
Component demo, not a trained model — SegFormer decoder channel projections and fusion across two supplied resolutions; no overlapping patch embedding or transformer blocks. 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])
}
fine<-matrix(0:7,nrow=4,byrow=TRUE)/8; coarse<-matrix(c(.2,.5,.8),1)
w_f<-matrix(c(1,.2,.3,.8),2,byrow=TRUE)
w_c<-matrix(c(.2,.1,.5,.4,.3,.7),3,byrow=TRUE)
projected_f<-fine%*%w_f; projected_c<-(coarse%*%w_c)[rep(1,4),,drop=FALSE]
fused<-cbind(projected_f,projected_c)
class_prob<-softmax(fused%*%matrix(c(1,-1,.2,.3,.4,-.2,-.1,.2),4,byrow=TRUE))
stopifnot(all(dim(fused)==c(4,4)),max(abs(rowSums(class_prob)-1))<1e-12)
print(list(fused_features=fused,two_class_probabilities=class_prob))
Sources
- Source 1arxiv.org
- Source 2github.com
From the CodeSplash reference, entry VIS013.