Back to paper library
arXiv 2023ICCV 2023SegmentationPaper notes

SAM

One-Finger Kung Fu

Original paper

Segment Anything

Paper authors

Alexander Kirillov · Eric Mintun · Nikhila Ravi …

Show all 12 authors

Alexander Kirillov · Eric Mintun · Nikhila Ravi · Hanzi Mao · Chloe Rolland · Laura Gustafson · Tete Xiao · Spencer Whitehead · Alexander C. Berg · Wan-Yen Lo · Piotr Dollár · Ross Girshick

Publication
ICCV 2023Conference
First submitted to arXiv
arXiv:2304.02643
Cite this paper · BibTeX

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

@misc{segmentationsam2023,
  title = {{Segment Anything}},
  author = {Alexander Kirillov and Eric Mintun and Nikhila Ravi and Hanzi Mao and Chloe Rolland and Laura Gustafson and Tete Xiao and Spencer Whitehead and Alexander C. Berg and Wan-Yen Lo and Piotr Dollár and Ross Girshick},
  year = {2023},
  eprint = {2304.02643},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2304.02643}
}
On this page

In the spring of 2023, ChatGPT had just turned "foundation model" into an industry buzzword. Language models are pretrained on web-scale text, and afterwards a change of prompt is enough to have them translate, summarize or write code; many tasks don't even need fine-tuning.

Image segmentation had nothing like this. The models in the previous few notes, whether PSPNet, Mask R-CNN or Mask2Former, were all trained on fixed datasets with fixed classes; change the domain or the set of classes, and you had to relabel data and retrain.

In April 2023, Alexander Kirillov and eleven co-authors at Meta AI (FAIR) released Segment Anything, together with the model, an online demo and a dataset of more than a billion masks. Click anything in an image on the web page and it cuts that thing out, whether it's an emu, a backpack or a single letter on a sign.

Defining the Problem

Original Figure 1: (a) the task, where the model takes an image and a segmentation prompt (points, a box, a rough mask, or text such as "cat with black ears") and outputs a valid mask; (b) the model, where the outputs of the image encoder and the prompt encoder go together into a lightweight mask decoder; (c) the data, where model and data cycle into each other, the model helping with annotation and the data then training the model, with a summary of the SA-1B dataset below: more than 1 billion masks, 11 million images, privacy-respecting, licensed images.
Original Figure 1, Kirillov et al., from PDF page 1, arXiv license, scholarly quotation.

The authors want a foundation model for segmentation, and they break the problem into three intertwined questions. What task lets a model generalize zero-shot to new data? What model architecture does it need? And what data should it be trained on?

For language models, the answer is "predict the next word" plus the endless supply of text on the web. Segmentation has neither. The web holds no large supply of ready-made masks, and segmentation has no agreed-upon task that can serve as a pretraining objective and also be turned, through prompts, into all kinds of downstream tasks.

Promptable Segmentation

The authors define the task first. Given an image and a prompt in any form, such as foreground or background points, a rough box, a rough mask or even a piece of text, the model has to return a valid mask.

Everything hinges on the word "valid." A point on someone's shirt could mean the shirt, or the person wearing it. When the prompt itself is ambiguous, the model doesn't have to guess which one the user has in mind, but it does have to return a reasonable mask for at least one of them. The authors compare this to language models, which also have to give a coherent answer to a vague question.

This task is both the pretraining objective and the inference interface. Any downstream task that can be turned into a prompt can use it directly. For example, if you have a cat detector, hand the boxes it outputs to SAM as prompts and you get instance segmentation of cats. The authors liken this use to CLIP's role in DALL·E, with the model as one component of a larger system.

Solving the Problem

Model

Original Figure 4: SAM overview. A photo of scissors goes through a large image encoder to produce an image embedding; the mask prompt at the bottom goes through convolutions and is added to the image embedding, while point, box and text prompts go through the prompt encoder; the mask decoder combines the two and outputs three valid masks, each with a score, each outlining a different extent of the scissors.
Original Figure 4, Kirillov et al., from PDF page 5, arXiv license, scholarly quotation.

The task makes three demands on the model: it has to accept all kinds of prompts, respond interactively in real time, and handle ambiguity. SAM's answer is to split the model into a heavy half and a light half. The heavy image encoder runs only once per image; the light prompt encoder and mask decoder run once for every new prompt.

We'll take one photo and one click through it.

Image encoder. The photo first has its long side resized to 1024 and its short side padded, making it 1024×10241024\times1024. The encoder is an MAE-pretrained ViT-H/16; most layers use 14×1414\times14 windowed attention, with four global-attention layers interspersed. The 16×1616\times16 patches turn the output into a 64×6464\times64 grid, and a 1×11\times1 convolution and a 3×33\times3 convolution then compress the channels to 256. This 64×64×25664\times64\times256 image embedding is what every later prompt shares.

Prompt encoder. We clicked once, so the coordinates (x,y)(x, y) are first turned into a positional encoding, and a learnable embedding is added to say whether it's a "foreground point" or a "background point," giving a 256-dimensional vector. A box is represented by two vectors, one for the top-left corner and one for the bottom-right. Text goes to CLIP's text encoder. If the prompt is a rough mask, it's downscaled with convolutions and added directly onto the image embedding.

Mask decoder. This is the most ingenious part of SAM. A few learnable output tokens are inserted next to the prompt vectors; they work like ViT's [class] token, and we'll use them shortly to produce the masks. These tokens go together with the image embedding into a two-layer two-way Transformer, and each layer does four things:

  1. Self-attention among the tokens.
  2. Cross-attention with the tokens as queries over the image embedding, reading the image content.
  3. Each token passes through an MLP on its own.
  4. The other way round, cross-attention with the image embedding as queries over the tokens, writing the prompt information back into the image embedding.

Step 4 is what "two-way" means. DETR-style decoders only let the queries read the image; SAM also lets the image read the prompt, so the updated image embedding already knows where the user clicked.

After the two layers, the image embedding is upsampled 4× by two transposed convolutions to 256×256×32256\times256\times32. Each output token goes through a 3-layer MLP to become a 32-dimensional vector, whose pointwise dot product with the upsampled image embedding gives a 256×256256\times256 mask. This is the same approach as MaskFormer's dot product between queries and per-pixel embeddings.

This decoder is small. The transformer dimension is 256, dropping even to 128 inside the cross-attention; its computation is less than 1% of the image encoder's. Once the image embedding is computed, the prompt encoder plus mask decoder take about 50 milliseconds on a CPU in a web browser, which is why the online demo can respond in real time.

Handling Ambiguity

If the model output only one mask, then faced with an ambiguous point it would learn to average the possible answers, and the result would look like none of them.

Original Figure 3: four columns of images, each with a single green point prompt; the top, middle and bottom rows are the three valid masks SAM outputs for the same point. In the first column the point is on an emu, and the three masks are, in order, the whole bird, the body without the legs and the head; in the second column the point is on a backpack, and the masks are the whole person, the backpack and a small pocket on the backpack; the third column shows different extents of a hand and the thing it holds; in the fourth column the point is on a ZURICH sign, and the three masks outline different extents of the lettering and logo, from large to small.
Original Figure 3, Kirillov et al., from PDF page 4, arXiv license, scholarly quotation.

SAM's approach is to always output three masks for each prompt. The authors observed that nested masks usually go at most three levels deep: whole, part and subpart. In the second column, the same point could be the whole person, the backpack or the pocket on the backpack.

During training all three masks are compared with the annotation, but the gradient is backpropagated only from the one with the lowest loss. This way each mask can specialize in one level instead of being forced to average. There is also a small prediction head that estimates each mask's IoU with the real object for ranking; in applications you can pick the highest-scoring mask.

When there is more than one prompt, the ambiguity usually disappears and the three masks become very similar. In that case a fourth output token is used instead, outputting just one mask.

Training by Simulated Interaction

During training, the authors simulate a user correcting step by step, running 11 rounds per mask:

  • In round 1, a foreground point or a box is given at random. The box gets noise with a standard deviation of 10% of the side length, simulating a user who draws a little imprecisely.
  • In the next 8 rounds, each round samples one point from the region where the previous prediction and the annotation disagree. Missed areas get a foreground point, over-drawn areas a background point; the mask logits from the previous round are also passed in as a prompt.
  • Another 2 rounds give no new points, so the model learns to refine its own output.

The mask loss is focal loss plus dice loss at a ratio of 20 to 1; the IoU prediction head uses mean squared error. Because the decoder is so light, running 11 rounds per update isn't expensive. The full model was trained on 256 A100s for 68 hours, about two epochs of SA-1B, with no data augmentation at all.

Data Engine

With the model and the task in place, what remains is data. The web holds no large supply of masks, so the authors had the model help with annotation and then trained the model on the annotated data, cycling through three stages.

Stage 1: assisted-manual. Professional annotators click foreground and background points in a browser, SAM gives a mask in real time, and the annotators touch it up with a brush and eraser. There's no restriction on categories; objects ("things") and background regions ("stuff") are both labeled, and if a mask takes more than 30 seconds, they move on to the next image. The model was retrained 6 times as data accumulated, the encoder was switched from ViT-B to ViT-H, and the average annotation time per mask dropped from 34 seconds to 14. The paper's comparison is that this is 6.5 times faster than COCO's mask annotation. This stage collected 120,000 images and 4.3 million masks.

Stage 2: semi-automatic. The masks from the first stage were used to train a generic "object" box detector, which fills in the confident masks automatically, and the annotators only label what's still missing. The goal is more diversity, letting annotators spend their effort on less conspicuous objects. Masks per image went from 44 to 72, and this stage collected another 180,000 images and 5.9 million masks.

Stage 3: fully automatic. By now the model is strong enough and can also handle ambiguity. The authors lay a 32×3232\times32 grid of points over each image, have SAM output three levels of masks for each point, and then pass them through three filters. The predicted IoU has to be high enough. The mask has to be "stable," meaning that binarizing the probability map at the two thresholds 0.5−δ0.5-\delta and 0.5+δ0.5+\delta gives roughly the same result. Finally, NMS removes duplicates. Small objects get a second pass on zoomed-in local crops.

All 11 million images were run through this, yielding 1.1 billion masks; that is SA-1B. The final dataset contains only the fully automatically generated masks, which make up 99.1% of the total.

How was the quality of the automatic masks checked? The authors randomly picked 500 images, about 50,000 masks, asked professional annotators to correct them until satisfied, and then compared before and after. For 94% of the masks, the IoU between the versions before and after correction exceeded 90%, and for 97% it exceeded 75%. For reference, earlier studies put agreement between different annotators at about 85% to 91% IoU.

Discussion

All of SAM's experiments are zero-shot transfer; four of the five tasks differ greatly from the training task, and none of the datasets appear in the training data.

How Well Can One Point Cut?

The first experiment is the closest to the training task, giving one foreground point and checking how well the mask is cut. The authors collected 23 datasets, ranging from underwater and microscopy to first-person views and fisheye lenses. The point is placed at the "center" of the annotated mask, meaning the position farthest from the boundary, and the main comparison is RITM, a strong baseline for interactive segmentation.

Original Figure 9: (a) SAM's IoU minus RITM's on 23 datasets, with orange bars for the 16 datasets where SAM does better, the highest being PPDLS, 46.9 ahead, and blue bars for the 7 where it does worse, the lowest being GTEA, 21.4 behind; the dot in each row is the "oracle" result, picking the mask among the three that best fits the annotation, and every dot sits to the right of 0. (b) Quality scores (1 to 10) given by annotators on 7 datasets, ordered roughly from top to bottom as the annotations, SAM, single-output SAM and RITM. (c)(d) Mean mIoU as the number of points grows from 1 to 9, (c) with center points and (d) with random points, with four lines for SAM, RITM, SimpleClick and FocalClick; at 1 point SAM is highest, and the gaps narrow as points are added.
Original Figure 9, Kirillov et al., from PDF page 9, arXiv license, scholarly quotation.

Look at (a). SAM beats RITM on 16 datasets, by nearly 47 points at most; it also loses on 7, with GTEA down 21.4. But the dot in each row is the "oracle," picking from the three masks the one closest to the annotation, and then SAM wins on all 23 datasets. Much of the losing comes from ambiguity; the highest-scoring mask SAM picks isn't at the same level as what the annotator originally outlined.

Automatic metrics have this blind spot, so the authors also ran a human rating study (b). Annotators scored masks from 1 (a mess) to 10 (pixel-perfect); SAM mostly landed between 7 and 9 and was significantly higher than RITM on every dataset. On DRAM and IBD, two datasets where SAM loses on the automatic metric, the human ratings actually favor SAM.

(c)(d) show the gaps between methods narrowing as the number of points grows. The authors also concede that SAM isn't optimized for refinement at very high IoU.

Tasks It Never Learned

The next four tasks are all assembled through prompt engineering; SAM itself is unchanged.

Edge detection (BSDS500). Lay a 16×1616\times16 grid of points to get 768 masks, then apply Sobel filtering to the masks' probability maps to extract edges. SAM's ODS is .768; HED, trained specifically on BSDS500 in 2015, gets .788, EDETR from 2022 gets .840, and the classic Canny gets .600. SAM draws more edges than the annotations contain, some of them plausible edges the annotators didn't label, so its recall at 50% precision is very high.

Object proposals (LVIS v1, AR@1000). The comparison is ViTDet-H, trained on LVIS, and the authors also note that this practice of "using a detector as a proposal generator" inflates AR to begin with. SAM gets 59.3 overall, ViTDet-H 63.0. Broken down, SAM does better on medium objects (81.6 vs 80.8), common classes (63.9 vs 63.3) and rare classes (65.8 vs 58.3), roughly ties on large objects (86.9 vs 87.0), and loses to ViTDet on small objects and frequent classes. A single-output SAM that doesn't handle ambiguity gets only 54.9 overall.

Instance segmentation. Use ViTDet's boxes as prompts and let SAM draw the masks:

MethodCOCO APLVIS AP
ViTDet-H (fully supervised)51.046.6
SAM (zero-shot, segmentation only)46.544.7

SAM loses on AP, but looking at the outputs, the authors felt SAM's boundaries were crisper, so they ran another human rating study. On LVIS ground-truth boxes, SAM's average score is 8.1 and ViTDet-H's 7.9; the LVIS annotations themselves score 8.6, and COCO's 7.6. The authors' guess is that ViTDet learned the particular biases of the COCO and LVIS annotations, for example that LVIS masks are all simple polygons with no holes, and SAM, never trained on this data, naturally couldn't pick them up.

Text to mask. SA-1B has no text annotations at all, so the authors used a clever workaround. During training, CLIP image embeddings are extracted from the regions of manually annotated masks and used as the first prompt; since CLIP's image and text embeddings are aligned, swapping in CLIP text embeddings at inference also works. Prompts like "a wheel" and "beaver tooth grille" both segment the right object; when "a wiper" fails, adding one point fixes it. The authors position this as a proof of concept.

Data and Model Size

Last come the ablations (Figure 13 of the paper), all run in the single-point setting on the 23 datasets.

Original Figure 13: the left shows the data stages used for training, in four groups (manual, plus semi-automatic, plus automatic, and automatic only), with dark bars for 1-point mIoU and light bars for the oracle; the middle shows mIoU at 1, 2, 3 and 5 points with 0.1M, 1M and 11M training images; the right shows mIoU for the image encoders ViT-B (91M), ViT-L (308M) and ViT-H (636M).
Original Figure 13, Kirillov et al., from PDF page 12, arXiv license, scholarly quotation.

The left plot shows that each data stage helps. Using all three stages together requires oversampling the manual and semi-automatic masks 10×, which makes training a hassle; using only the automatic masks is just about 0.5 mIoU lower, so by default only the automatic masks are used.

The middle plot is about data size. With only 100,000 images, results drop clearly; with 1 million, about 10% of the total and still around 100 million masks, the results are about the same as with all 11 million.

The right plot is about encoder size. ViT-H is much better than ViT-B, and only slightly better than ViT-L. The authors' conclusion is that scaling the image encoder further didn't look very worthwhile at the time.

Limitations

The authors list these quite candidly in their discussion. SAM misses fine structures, occasionally produces small disconnected fragments, and its boundaries aren't as sharp as those of methods that "zoom in and then segment." Given many points, dedicated interactive segmentation methods do better. The prompt part is real-time, but with the heavy image encoder included, the system as a whole isn't. Text prompts are only an initial exploration. How to design simple prompts that achieve semantic or panoptic segmentation is something the authors themselves don't yet know.

Conclusion

Return a valid mask for whatever prompt comes in, and three levels of masks when there's ambiguity; that is the new task SAM defined. The heavy encoder runs once per image, the light decoder once per prompt; the data is labeled by the model itself and fed back into training, ending up as 1.1 billion masks. Some of its zero-shot results can't catch up with fully supervised models, yet the human ratings often come down on its side.

It can cut, but it can't name. The masks have no classes; to know what was cut, you have to attach another model. The later Grounded SAM first finds boxes with an open-vocabulary detector and then hands them to SAM to cut, while HQ-SAM, MobileSAM and MedSAM shore up boundaries, speed and medical imaging, respectively.

The official SamPredictor has you call set_image and then predict, which is exactly how this architecture is meant to be used. The most expensive part, the encoder, runs only once, at set_image; click the same image a hundred times and it's still computed only once.