Back to paper library
arXiv 2023Information Fusion 2024SegmentationPaper notes

ViTMatte

It's About the Hair

Original paper

ViTMatte: Boosting Image Matting with Pretrained Plain Vision Transformers

Paper authors

Jingfeng Yao · Xinggang Wang · Shusheng Yang · Baoyuan Wang

Publication
Information Fusion 2024Journal
First submitted to arXiv
arXiv:2305.15272
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{segmentationvitmatte2023,
  title = {{ViTMatte: Boosting Image Matting with Pretrained Plain Vision Transformers}},
  author = {Jingfeng Yao and Xinggang Wang and Shusheng Yang and Baoyuan Wang},
  year = {2023},
  eprint = {2305.15272},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2305.15272}
}
On this page

A segmentation model sorts every pixel into "yes" or "no," and most of the time that's enough. But with hair, animal fur or the sheer tulle of a wedding dress, the pixels along the edge are often a mix of foreground and background colors. Force them to 0 or 1, and once the background is swapped you're left with a strange hard outline.

Image matting deals with exactly this situation. The answer it wants is each pixel's opacity, a number between 0 and 1.

Around 2023, the mainstream matting network used a hierarchical backbone such as ResNet or Swin to extract multi-level features, followed by a carefully designed decoder that fused the different scales while restoring detail. Meanwhile, over in object detection, ViTDet had already shown that an unmodified plain ViT with a very simple adapter could do very well.

Jingfeng Yao and Xinggang Wang of Huazhong University of Science and Technology, Baoyuan Wang of Xiaobing.AI and their co-authors wanted to know whether a plain ViT could be used the same way for matting, a task that lives and dies by detail.

Defining the Problem

Diagram drawn for this note, four panels from left to right. Image: a fuzzy-edged orange ball of fur on a green background. trimap: a black background with the ball's center in white and a gray band around its edge. alpha matte: a white ball of the same shape on black, its edge fading out gradually. New background: the ball placed on a blue background with its semi-transparent edge preserved. Below is the compositing equation I = αF + (1 − α)B.
Drawn for this note from the trimap definition and compositing equation in Section 3.1 of the paper; shapes are illustrative.

Matting starts from the compositing equation. The color II of each pixel can be seen as a blend of the foreground color FF and the background color BB, weighted by the opacity α\alpha:

I=αF+(1−α)BI = \alpha F + (1 - \alpha) B

α=1\alpha = 1 is pure foreground, α=0\alpha = 0 is pure background, and the edges of the hair fall somewhere in between. Once α\alpha is estimated, swapping out BB composites the subject onto a new background.

The trouble is that this system of equations can't be solved. Each pixel gives only three observed numbers, its RGB values, but there are seven unknowns, three colors for FF, three for BB, plus α\alpha. So matting usually asks the user to draw a trimap first, marking the areas that are definitely foreground and definitely background, and only the gray zone left over is handed to the algorithm. ViTMatte encodes the trimap as a grayscale image, 0 for background, 1 for foreground and 0.5 for unknown, and concatenates it with RGB into a 4-channel input.

The authors identify two difficulties in using a plain ViT for matting.

The first is compute. Every ViT layer does global attention over all tokens, at a cost proportional to the square of the token count. Matting images are routinely more than a thousand pixels wide; a 2048×2048 image cut into 16×16 patches gives 16,384 tokens, and the attention matrix of a single head alone has about 270 million elements.

The second is detail. A ViT compresses each 16×16 block into one vector right at the start, and the feature map it finally outputs is only 1/16 of the original resolution. A strand of hair is often just one or two pixels wide, and that kind of information is easily blurred away at the patch embedding step. ViTDet upsamples the 1/16 features into a pyramid with deconvolutions, but upsampled features simply don't contain the details that were already thrown away.

Solving the Problem

Architecture diagram drawn for this note. At top left is the input, RGB + trimap (4 ch), which goes into ViT-S; the ViT's 12 layers are split into 4 groups, each with two window-attention layers and one global-attention layer followed by a conv neck, and the output is 1/16 features (32×32). The input also takes a second path down through the ConvStream, giving D0 (Input), D1 (1/2), D2 (1/4) and D3 (1/8). The bottom row is the fusion path, which starts at 1/16 and upsamples leftward to 1/8, 1/4, 1/2 and 1, each step taking in the detail features of the same resolution directly above it, and finally outputs the alpha matte at full resolution.
Drawn for this note from Sections 3.2–3.4 of the paper and the official code; sizes assume a 512×512 input and ViT-S.

ViTMatte's design principle is to leave the ViT alone as much as possible. The architecture has two parts, a slightly modified plain ViT that understands the image and a very light Detail Capture Module (DCM) that restores the detail.

Follow the shapes for a 512×512 training crop and ViT-S. The 4-channel input is cut into 16×16 patches, giving 32×32 = 1,024 tokens of 384 dimensions each. After the 12 Transformer layers it's still 32×32×384. The DCM then upsamples this 1/16 feature map all the way back to 512×512 and outputs a single-channel alpha matte.

Most Layers Only Look at Their Neighbors

The first modification is mixed attention. The authors split the 12 layers evenly into 4 groups of 3; only the last layer of each group does global attention, and the first two switch to window attention. The official configuration uses 14×14 windows, so each token attends only to the 196 tokens around it.

The reasoning is straightforward. The trimap already tells the model where the foreground and background are, so the global semantics are largely settled. What the network really has to work hard on is local detail, one small patch at a time, inside the unknown region, which is exactly where window attention excels.

A Convolution After Each Group

The second modification adds a conv neck after each group of Transformer layers. It's a ResNet bottleneck block (1×1, 3×3, 1×1 convolutions), added back residually.

The authors' explanation is that attention tends to pick up low-frequency information, while convolution acts like a high-pass filter that can extract high-frequency signals such as edges and textures. With a residual connection, what the Transformer has learned isn't disrupted, and the convolution only has to add the detail back in.

A Separate Path Just for Detail

Neither modification solves the 1/16 problem, and that is what the DCM is designed for. It has two parts.

The first is the ConvStream, a separate path that starts straight from the raw input. It has only 3 conv layers, each a stride-2 3×3 convolution with BatchNorm and ReLU, giving features D1D_1, D2D_2 and D3D_3 at 1/2, 1/4 and 1/8 resolution, with 48, 96 and 192 channels. The raw input itself serves as D0D_0.

The second is fusion, which starts from the ViT's output features F4F_4 and upsamples by 2× at each step:

Fi−1=Conv(Upsample(Fi)⊕Di−1)F_{i-1} = \mathrm{Conv}\big(\mathrm{Upsample}(F_i) \oplus D_{i-1}\big)

⊕\oplus is concatenation along the channel dimension. Each step upsamples the features 2× with bilinear interpolation, concatenates the detail features of the same resolution, and passes the result through one 3×3 conv. After four steps it's back to full resolution, with 256, 128, 64 and 32 channels in turn; a final matting head squeezes this down to 1 channel with two conv layers, and after a sigmoid that's alpha.

The ViT features are used only once here, with no pyramid built from them. Within the DCM, the ConvStream has about 0.2M parameters and the fusion layers about 2.7M; for comparison, ViTDet's simple feature pyramid alone takes 5.6M.

Training

With the extra trimap channel in the input, the patch embedding of the pretrained weights no longer fits. The authors zero-pad the kernel from (D,3,P,P)(D, 3, P, P) to (D,4,P,P)(D, 4, P, P), so the extra channel has no effect on the output at first, and all other weights are reused unchanged. ViTMatte-S is initialized from DINO weights and ViTMatte-B from MAE.

The loss has three terms:

L=Lseparate ℓ1+Llap+Lgp\mathcal{L} = \mathcal{L}_{\text{separate } \ell_1} + \mathcal{L}_{\text{lap}} + \mathcal{L}_{\text{gp}}

The first is L1, but averaged separately over the unknown and known regions, with the two mean errors then added. The unknown region usually covers only a small part of the image, and if the whole image were averaged together, its error would be diluted by the large known area. The second is a Laplacian loss, which compares prediction and ground truth at every level of an image pyramid; the third compares their gradients, making the model more sensitive at boundaries and smoother locally.

The training data takes the 431 foregrounds of Adobe Image Matting and composites each onto 100 COCO backgrounds, for 43,100 images. Trimaps are generated from the ground-truth alpha by dilation and erosion, with a kernel size drawn at random between 1 and 30. Training runs 100 epochs on two V100s with AdamW and a learning rate of 5e-4; the pretrained ViT part additionally uses layer-wise learning-rate decay of 0.65.

Discussion

Composition-1k and Distinctions-646

The Composition-1k test set composites each of 50 foregrounds onto 20 VOC backgrounds. The metrics are computed only over the trimap's unknown region, and for all four, lower is better.

MethodSADMSEGradConnParams
MatteFormer23.804.038.6818.9044.8M
RMat22.873.97.7417.8427.9M
ViTMatte-S21.463.37.2416.2125.8M
ViTMatte-B20.333.06.7414.78—

ViTMatte-S has fewer parameters than RMat and is better on all four metrics; with ViT-B, its SAD is 2.54 lower than RMat's.

The gap is larger on Distinctions-646, where ViTMatte-B's SAD is 17.05 against 25.65 for the previous best, TransMatting. But this dataset has no official test trimaps, and each paper generates its own at random. The authors use erosion with kernel sizes of 1–30, and the text admits that the results depend on the trimaps. Discount these numbers a little when comparing them with other papers.

Ablations

All of the following ablations use ViT-S with DINO weights, train for only 10 epochs, and report SAD and MSE on Composition-1k.

The first question is how many global-attention layers to keep. FLOPs in the table are the compute for a 2048×2048 image, relative to using global attention in all 12 layers:

Global layersSADMSEFLOPs
12 (original ViT)29.836.381.00× (3.28T)
032.307.030.26×
229.635.810.38×
428.315.640.50×
828.405.820.63×

Switching everything to window attention really doesn't work, since the model can no longer see the whole image at all. But keeping 4 layers does better than the original ViT at half the compute. When the authors averaged the two kinds of attention maps and looked at them, window attention responded noticeably more strongly, while global attention was mostly not very active. For matting, looking at the whole image in every layer actually keeps the network from concentrating on detail.

Three blocks were tried for the conv neck. A single 3×3 conv brings SAD from 28.31 down to 27.99, a ConvNeXt block gets 27.84, and the ResNet bottleneck does best at 27.24, for only 2% more FLOPs.

The DCM has the most visible effect. With no detail features at all, MSE is about 13.3. Connecting just D0D_0, that is, feeding the original image straight into the last fusion step, brings MSE down to around 6.1 for less than 0.1M extra parameters. Adding D1D_1 through D3D_3 in turn lowers it further to about 5.1; one more level down to 1/16 brings the extra parameters to around 6.5M, and the result actually gets worse.

The authors also compare directly against ViTDet's simple feature pyramid:

Multi-scale featuresSADMSEParamsFLOPs (2048×2048)
ViTDet simple feature pyramid28.595.5731.5M5.81T
ViTMatte DCM27.245.1425.8M1.69T

Upsampling the 1/16 features with deconvolutions costs more parameters and more than three times the compute, and still does worse. For high-resolution matting, extracting detail separately from the original image is clearly a much better deal than upsampling semantic features.

Pretrained Weights

PretrainingViT-S SADViT-B SAD
From scratch59.8350.61
ImageNet-21k supervised29.4626.46
MAE—26.15
DINO27.6127.89
iBOT28.1728.73

Training from scratch gives nearly twice the SAD of the pretrained runs. Matting datasets have only a few hundred foregrounds, so a data-hungry architecture like ViT depends almost entirely on pretraining; and because ViTMatte doesn't modify the ViT itself, switching to another set of weights needs no architectural changes. For ViT-S, DINO works best; for ViT-B, MAE does.

The authors also computed the decoder's share of the model's parameters. For ViTMatte it's 8%; for other matting methods it ranges from 21% to 49%.

High-Resolution Inference

Training uses 512×512 crops, but inference often has to handle large images at full size, and here the 4 remaining global-attention layers become the bottleneck again. The authors propose a grid sample used only at inference. Before global attention, the tokens in every 2×2 neighborhood are split across four groups, and each group does global attention on its own. Each group has only a quarter of the tokens, but they are still spread evenly over the whole image.

On 2048×2048 images, GPU memory drops from 20.3G to 6.8G, while SAD only moves from 21.46 to 21.54.

This code isn't in the ViTMatte repo. In GitHub issue #10, someone reported that running ViTMatte-B inference on Distinctions-646 ran out of memory outright on an 80G A100. The authors replied that the grid sample implementation lives in vit.py of another project, Matte-Anything, and that reproducing the paper's Distinctions-646 results means swapping in that version of the Block's forward (Table 8's memory savings live in the repo next door; movers not included). After making the swap, another user said ViTMatte-B still couldn't run on high-resolution images, while MatteFormer could on the same machine; the authors' advice was to swap in xformers or FlashAttention yourself. The issue is still open.

Conclusion

ViTMatte showed that matting, too, can do without a custom-built backbone and an elaborate decoder. The plain ViT needs only two changes, window attention in most layers and a conv block after each group, plus a very shallow conv path pulled separately from the original image to restore detail. The decoder makes up only 8% of the parameters, and it set the best results of its time on both Composition-1k and Distinctions-646.

The assumption it leaves in place is the trimap. Every trimap in the paper is made from the ground-truth alpha by dilation and erosion; in real use, someone has to draw it. Two weeks later the authors released Matte Anything, which hands that step to SAM to generate automatically before ViTMatte does the matting. ViTMatte later made it into Hugging Face Transformers too, and the README cites more than 4 million downloads a month.

Looking back, this division of labor resembles a person retouching a photo, roughing out the large areas with an automatic selection first, then zooming in to trace the band of hair slowly by hand. ViTMatte gives the first job to the pretrained ViT and the second to those three conv layers.