Back to paper library
arXiv 2023NeurIPS 2023SegmentationPaper notes

HQ-SAM

A Single Kite Line

Original paper

Segment Anything in High Quality

Paper authors

Lei Ke · Mingqiao Ye · Martin Danelljan …

Show all 7 authors

Lei Ke · Mingqiao Ye · Martin Danelljan · Yifan Liu · Yu-Wing Tai · Chi-Keung Tang · Fisher Yu

Publication
NeurIPS 2023Conference
First submitted to arXiv
arXiv:2306.01567
Cite this paper · BibTeX

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

@misc{segmentationhqsam2023,
  title = {{Segment Anything in High Quality}},
  author = {Lei Ke and Mingqiao Ye and Martin Danelljan and Yifan Liu and Yu-Wing Tai and Chi-Keung Tang and Fisher Yu},
  year = {2023},
  eprint = {2306.01567},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2306.01567}
}
On this page

In the first few months after SAM came out, everyone was testing what it could segment. It turned out it could segment almost anything, just not very finely.

The slats of a chair back get smeared into one solid piece, an insect keeps only half its legs, and kite lines fare even worse, sometimes treated entirely as background and sometimes dragging the sky behind them into the mask. SAM was trained on 1.1 billion masks, but most of those masks were generated automatically by the model and were never labeled with fine structures in mind.

Lei Ke, Mingqiao Ye, Martin Danelljan and Fisher Yu of ETH Zurich, with collaborators from the Hong Kong University of Science and Technology and Dartmouth College, set out to fix SAM's boundaries; Lei Ke and several of the co-authors had earlier built Mask Transfiner for high-quality instance segmentation. But they didn't want to retrain SAM. The ViT-L version of SAM alone took 128 A100s to train, and once its weights are touched, its zero-shot abilities may well be lost.

Defining the Problem

Original Figure 1. SAM is in the top row and HQ-SAM in the bottom row, with the same red box or red star point prompt in each of the four examples. In the first, a bench, SAM smears the openwork carving of the backrest into one piece, while HQ-SAM cuts out the openings; in the second, a butterfly, SAM misses the antennae and legs; in the third, a metal rack on a wall, SAM paints a large part of the wall blue as well; in the fourth, a kite surfer, SAM mistakes most of the sky for foreground, with holes in it, while HQ-SAM segments only the person and the kite lines.
Original Figure 1, Ke et al., from PDF page 2, arXiv license, scholarly quotation.

The authors sort SAM's problems into two kinds. One is boundaries that are too coarse, where thin structures often vanish altogether, like the butterfly's antennae above. The other is getting the whole thing wrong in hard cases, most obvious in the rightmost example, where SAM is given a box around the person yet cuts out most of the sky too, with holes in the middle.

There are three intuitive ways to fix these problems. The authors tried all of them in the paper, and none works very well.

The first is to fine-tune SAM directly on high-quality data. It does improve on the new data, but zero-shot performance on COCO collapses along with it, which is the so-called catastrophic forgetting.

The second is to attach a refinement network after SAM and feed it the coarse mask and the image to clean up. CascadePSP and CRM are methods of this kind, and the problem, again, is that they easily overfit to the training data.

The third is to train only a small number of parameters, with CoOp-style learnable context tokens or LoRA. This forgets less, but the improvement is limited too.

HQ-SAM looks for a fourth way, leaving every one of SAM's original weights untouched and adding very few parameters so that the model outputs one more, finer mask.

Solving the Problem

Original Figure 3. The top half, on a blue background, is the frozen SAM: the image passes through the Image Encoder to give 64×64 features, which enter the two-layer Mask Decoder together with the Prompt Tokens and Output Tokens; the Output Tokens go through an MLP and take a point-wise product with the mask features upsampled by transposed convolutions, giving the SAM Mask. The bottom half, on an orange background, is the new, trainable part of HQ-SAM: an HQ-Output Token passes through the Mask Decoder with the other tokens and, once updated, goes through a new MLP; features from an early ViT layer and the final ViT layer, plus the decoder's mask features, are combined by Global-local Fusion into 256×256 HQ-Features, which take a point-wise product with the HQ-Output Token; a dashed line shows SAM's output being added in at inference for Error Correction, giving the HQ-SAM Mask.
Original Figure 3, Ke et al., from PDF page 4, arXiv license, scholarly quotation.

First, a quick recap of how SAM's mask decoder produces a mask. The image encoder outputs a 64×64, 256-dimensional feature map. Besides the prompt tokens representing the prompt, the decoder has 4 output tokens that play a role similar to DETR's object queries. These tokens and the image features attend to each other through the two decoder layers; afterwards, each output token passes through an MLP to become a set of dynamic weights, which are multiplied point-wise with the mask features upsampled to 256×256 to give a mask.

HQ-SAM changes only two things in this pipeline.

One More Output Token

The first is a new token, the HQ-Output Token, of size 1×256. It is concatenated with the original 4 output tokens and the prompt tokens and enters the frozen decoder, where in every layer it joins the other tokens in self-attention and in token-to-image and image-to-token cross-attention; it even shares each layer's MLP with the other tokens.

So by the end of the two decoder layers, the new token has seen the whole image, knows what the prompt refers to, and can read the other output tokens' judgments about the mask. Finally it goes through a newly added 3-layer MLP to become dynamic weights, which are multiplied with the high-quality features described below to give HQ-SAM's mask.

During training, only this token and its MLP are updated. It amounts to adding one extra seat in SAM's original decoder; the token in that seat learns specifically to correct the original output tokens' mistakes, and everyone else carries on as before.

Bringing Early Features Back

The second change replaces the feature map used in that multiplication. SAM's mask features come from the decoder upsampling the encoder's last-layer features, so they are strong semantically but have little detail left. HQ-SAM builds a separate HQ-Features map, summed from three sources:

  1. Features from an early layer of the ViT encoder, specifically the output after the first global-attention block, which for ViT-L is layer 6 of 24. This layer still retains more edges and local texture.
  2. Features from the last layer of the ViT encoder, which carry the full global semantics.
  3. The original mask features of SAM's decoder, which contain strong information about mask shape.

The first two are both 64×64, and each is upsampled to 256×256 with two transposed-convolution layers; the third goes through two 3×3 conv layers. Once all three are brought to the same 32 channels, they are added element-wise, and the new token's dynamic weights are multiplied with this map.

At inference, the authors simply add the logits of SAM's original output token to those of the HQ token and upsample the sum to 1024×1024, which the paper calls error correction.

44K Finely Annotated Masks

The trainable parts are just the HQ token, its 3-layer MLP and the three sets of fusion convolutions. For ViT-L, SAM has 1,191M parameters and HQ-SAM adds only 5.1M; inference speed goes from 5.0 to 4.8 images per second, and GPU memory stays at 7.6G.

For training data, the authors didn't use SA-1B. Instead they combined six existing, finely annotated datasets into HQSeg-44K, with 44,320 masks in over 1,000 classes: the training sets of DIS and ThinObject-5K, plus FSS-1000, DUTS, ECSSD and MSRA-10K. Training randomly mixes three kinds of prompt, boxes, points and coarse masks, with the coarse masks made by adding Gaussian noise to the ground-truth boundaries. On 8 RTX 3090s with batch 32, 12 epochs totaling 16.6K iterations finish in 4 hours.

Discussion

Four High-Quality Datasets

The main ablations are run on four datasets with extremely fine annotation, DIS, ThinObject-5K, COIFT and HR-SOD. The prompts are boxes derived from the ground-truth masks, and the metrics are mIoU and mBIoU, which measures boundaries.

MethodDISCOIFTHRSODThinObjectAvg.
SAM52.886.583.161.871.1
SAM + context token62.287.785.073.177.0
SAM + HQ token (SAM mask feature)66.089.286.175.479.2
HQ-SAM70.490.186.979.981.8

Values are mBIoU.

Average mBIoU rises from 71.1 to 81.8. But these four columns need to be read separately. The training sets of DIS and ThinObject-5K are already part of HQSeg-44K, and only COIFT and HRSOD are data the model hasn't seen. The two columns with the biggest gains, DIS up 17.6 and ThinObject up 18.1, happen to be exactly the two in-distribution ones; the truly zero-shot COIFT and HRSOD gain 3.6 and 3.8. The paper's text does say that 8 of its 10 test datasets are zero-shot, but "the average over four datasets" lumps the two situations together, so remember to separate them when reading the numbers.

The contribution of each of the three features was ablated as well. With SAM's mask features alone, average mBIoU is 79.2; adding the fusion convolutions gives 80.1, adding the last-layer ViT features 81.3, and using all three 81.8. Removing the mask features and using only the last-layer ViT features drops average mIoU straight to 15.1. The paper offers no further explanation, but this at least shows that SAM's original mask features are the mainstay, with the other two features adding detail on top. Fusing with a conventional FPN instead is also worse, with mIoU falling from 89.1 to 87.4.

Compared with Fine-Tuning

This comparison makes the strongest case for HQ-SAM's design. The boxes for COCO, on the right, come from a FocalNet-DINO detector trained on COCO, and SAM is fully zero-shot here:

Method4-dataset mBIoUCOCO APBCOCO AP
SAM71.133.348.5
Train all of SAM12.20.25.5
CascadePSP refinement74.62.813.4
CRM refinement75.415.928.7
Fine-tune SAM's decoder79.59.019.5
Fine-tune only SAM's output token79.733.748.7
HQ-SAM81.834.449.5

Training the whole of SAM on the 44K images breaks both sides. Fine-tuning the decoder improves on the high-quality data, but COCO falls from 48.5 to 19.5, and attaching a refinement network ends the same way. The version that fine-tunes only the output token doesn't forget, but its improvement is clearly smaller than HQ-SAM's.

The authors also tried LoRA and adding adapters to the encoder, which dropped COCO APB to 28.6 and 29.6 respectively. Their conclusion is that it's best not to touch a single parameter of the encoder.

Strict Boundary Thresholds

Original Figure 4. Two line charts, with the BIoU threshold from 0.5 to 0.9 on the horizontal axis and the share of predicted masks above the threshold on the vertical axis. On the left, COIFT, SAM falls from 97.9 to 49.6 and HQ-SAM from 99.6 to 69.3; on the right, HRSOD, SAM falls from 95.5 to 40.1 and HQ-SAM from 98.6 to 53.3. The stricter the threshold, the wider the gap between them.
Original Figure 4, Ke et al., from PDF page 7, arXiv license, scholarly quotation.

This figure covers only the two zero-shot datasets. At loose thresholds the two lines nearly overlap; at a BIoU of 0.9, which demands an almost exact boundary fit, only half of SAM's masks pass on COIFT, against nearly 70% for HQ-SAM.

Even at the loosest threshold, 0.5, there's a visible difference. On COIFT, 2.1% of SAM's masks fail, against only 0.4% for HQ-SAM, which the authors convert into an 81% reduction in errors. A mask that can't even reach a BIoU of 0.5 is usually not a little off at the boundary; a large chunk of it is wrong.

Original Figure 6. Nine examples, each with three images: the original image, the cross-attention map of SAM's original output token in the decoder's last layer, and the attention map of the HQ-Output Token. The SAM token's attention concentrates on the body of the object, while the HQ token's attention spreads over the object's outline, thin rods and thin lines, such as railings, wheel spokes and slender poles.
Original Figure 6, Ke et al., from PDF page 10, arXiv license, scholarly quotation.

Plotting the new token's attention in the decoder's last layer shows that it really does watch what the original token overlooked: outlines, railings, spokes and other thin, elongated structures.

Other Tasks

HQ-SAM gains 1.1 APB on COCO and 1.3 strict-boundary AP on UVO, and on HQ-YTVIS, for video instance segmentation, APB goes from 30.2 to 34.0. On BIG, a high-resolution dataset, with coarse masks from PSPNet as prompts, mBIoU jumps from 41.8 to 75.1; SAM is clearly more sensitive to inaccurate prompts. The supplementary material also adds noise to the ground-truth boxes, and the larger the noise, the larger the gap; at a noise scale of 0.4, average mBIoU is 39.8 vs. 60.3. HQ-SAM never saw noisy boxes in training.

Another comparison is also in the supplementary material. With the same training recipe but 44K images sampled at random from SA-1B, average mBIoU actually drops from 71.1 to 70.1. Here data quality matters more than the architecture.

Finally, HQ-SAM's bottleneck is the same as SAM's, that heavy ViT encoder. The authors also built Light HQ-SAM, which swaps the encoder for MobileSAM's TinyViT and runs at 41.2 images per second, raising COCO AP from MobileSAM's 44.3 to 45.0 for only 1.7MB more.

Conclusion

HQ-SAM adds a capability to a large frozen model without changing its weights or bolting on an add-on, just by placing one more token in the decoder and letting it read earlier features. For 5.1M parameters and 4 hours of training, it gets noticeably better boundaries and keeps its zero-shot ability.

Its numbers need a little unpacking. Two of the four datasets in the average share a distribution with the training data; the truly zero-shot boundary gain is about 3 to 4 points of mBIoU, and on general scenes like COCO it's only about 1 point. These gains matter mainly where fine boundaries are required, such as annotation tools and image editing. Later, projects that build annotation and tracking on SAM, such as Grounded-SAM and SAM-PT, added HQ-SAM support, and at the end of 2024 the authors themselves carried the same approach over to SAM 2 as HQ-SAM 2.

The official code has a parameter hq_token_only that defaults to False, which is the paper's correction mode of adding the two logits. A comment in the official demo recommends switching it to True when the image contains a single object, to use the HQ token's output directly; for multi-object scenes and quantitative evaluation, keep the default.