Search

Search papers and lessons

Segment Anything

Alexander Kirillov, Eric Mintun, Nikhila Ravi et al. · 2023

SAM is a segmentation model that returns a valid mask for any point, box or text prompt, trained with a model-in-the-loop data engine that produced 1.1 billion masks for zero-shot transfer.

On this page

  • Colour = topic mix
  • Calculus
  • Architectures
  • Probability
  • Neural network basics
  • Linear algebra
  • Computer vision
  • Sign in to see your progress

TL;DR

Segmentation models were trained for one fixed set of classes, and there was no web-scale supply of masks to train a general one. Kirillov et al. define a promptable task, where any point, box or mask prompt must return a valid mask, and build a model and a data engine around it. The engine produced SA-1B, with 11 million licensed images and 1.1 billion masks. The resulting model, SAM, transfers zero-shot to 23 new datasets and to several tasks it was never trained on, by prompt engineering.

Where you'll see it: interactive "click to select an object" tools, and as the segmentation component inside larger systems that get their prompts from a detector or a language model.

The problem

Language models gain generality from web text, which is abundant. Segmentation has no equivalent. Masks, the per-pixel outlines of objects, are expensive to draw, so datasets are small and cover fixed label sets. A model trained on one of them does well on its own categories and poorly on anything else, and combining datasets does not solve this because each dataset has its own definition of an object.

The paper asks three coupled questions: what task would let a model generalize, what architecture would serve that task, and what data could train it. Its answer is to treat all three together, rather than to fix the data first.

Key idea

The task is promptable segmentation: given any prompt, return a valid mask. A prompt can be foreground or background points, a rough box, a mask or free-form text. A valid mask means that when a prompt is ambiguous, the output should be a reasonable mask for at least one plausible object. A point on a shirt may mean the shirt or the person wearing it. The model should return a sensible answer for either reading.

The model is split so the expensive part runs once. A heavy image encoder computes an embedding for the image. A lightweight prompt encoder and mask decoder then answer each prompt against the same embedding, so many prompts cost little more than one. The paper reports about 50 ms per prompt on a CPU in a web browser.

The data comes from a loop. Early in the loop, annotators label masks with the model's help. Later, the model labels most masks itself, and annotators only check or add to them. Each round retrains the model on the newer masks.

flowchart LR
    A[Train SAM on public masks] --> B[Stage 1: annotators click with SAM help]
    B --> C[Retrain SAM]
    C --> D[Stage 2: SAM proposes confident masks, annotators add the rest]
    D --> E[Retrain SAM]
    E --> F[Stage 3: SAM labels a grid of points automatically]
    F --> G[SA-1B: 1.1B masks on 11M images]

The method

The task and why it is trained the way it is

Pre-training simulates a sequence of prompts for each training example. The paper adapts this from interactive segmentation, but with a different goal. Interactive systems aim to reach a correct mask after enough clicks. SAM must give a valid mask for any prompt, including an ambiguous first click, because the data engine uses it on single prompts before a human has corrected anything.

Zero-shot transfer follows from this. If a detector can find cats, its boxes can be used as prompts, and instance segmentation of cats follows without training. The paper treats this as "prompt engineering", by analogy with prompting a language model.

Ambiguity: three outputs and the minimum loss

A single output averages several valid masks when the prompt is ambiguous, and an average of a part and a whole is usually a bad mask. SAM predicts three masks per prompt. The authors chose three because nested masks are at most about three deep: whole, part and subpart. Each mask comes with a predicted IoU, which ranks them for the user.

During training only the lowest loss mask is backpropagated. Each of the three masks gets a loss ℓk\ell_k, and the gradient comes from the minimum:

Lmask=min⁡k∈{1,2,3}ℓk,ℓk=20 Lfocal(m^k,m)+Ldice(m^k,m)\mathcal{L}_{\text{mask}} = \min_{k \in \{1, 2, 3\}} \ell_k, \qquad \ell_k = 20\, \mathcal{L}_{\text{focal}}(\hat{m}_k, m) + \mathcal{L}_{\text{dice}}(\hat{m}_k, m)

The 20:1 ratio of focal to dice loss follows earlier work. The IoU head is trained with a mean-squared error to the true IoU of the chosen mask, added with weight 1.

Example
Minimum loss over three masks (illustrative numbers)

Suppose one prompt on a person's shirt gives three candidate masks, with losses ℓ1=0.8\ell_1 = 0.8 for the shirt, ℓ2=0.3\ell_2 = 0.3 for the person and ℓ3=0.6\ell_3 = 0.6 for an arm.

  1. The minimum is min⁡(0.8,0.3,0.6)=0.3\min(0.8, 0.3, 0.6) = 0.3.
  2. Only the person mask's loss gives a gradient, so the network is pushed to make that output a good mask.
  3. The other two outputs get no gradient on this example, so they are free to specialize. Over many examples, different outputs come to cover different levels of the nesting.

The numbers are invented to show the mechanism. The paper states only the mechanism, not these values.

The model

The image encoder is a ViT-H/16, pre-trained with masked autoencoding (MAE), and adapted with windowed attention plus four global attention blocks. It takes a 1024 by 1024 input, and its output is a 64 by 64 embedding, a 16-fold downscale. Because it runs once per image, the paper accepts its cost.

Prompts are encoded in two ways. Points and boxes become positional encodings summed with learned embeddings for each prompt type. Free-form text goes through CLIP's text encoder. Dense mask prompts are convolved and added element-wise to the image embedding.

The mask decoder is a two-layer modified transformer decoder. Its prompt tokens attend to the image, and the image attends back to the prompt, so both are updated in each block. A dynamic head then turns an output token into a linear classifier that scores each image location.

Training recipe

The default model uses AdamW with β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, a learning rate of 8×10−48 \times 10^{-4} after a 250-iteration warmup, and a step decay by a factor of 10 at 60k and 86,666 iterations. It trains for 90k iterations at batch size 256 images, which the authors describe as about two epochs over SA-1B. Weight decay is 0.1 and drop path 0.4, and no data augmentation is used. Training ran on 256 GPUs. During training each mask gets up to 11 prompt rounds: one initial prompt, eight sampled points, and two rounds with no new prompt, so the decoder learns to refine its own output.

The data engine and SA-1B

The engine has three stages, and the numbers the paper gives show how the work shifts.

In the assisted-manual stage, professional annotators click foreground and background points in a browser tool powered by SAM. Average time per mask fell from 34 seconds to 14 seconds as the model was retrained six times, and the average masks per image rose from 20 to 44. This stage produced 4.3M masks from 120k images.

In the semi-automatic stage, a box detector trained on the first-stage masks proposes confident objects. Annotators then label the remaining objects. This stage added 5.9M masks in 180k images, for a total of 10.2M, and masks per image rose from 44 to 72. The paper says the purpose is to increase diversity, by pushing annotators toward less prominent objects.

In the fully automatic stage, SAM is prompted with a 32 by 32 grid of points. For each point it returns several masks, and the authors keep the confident ones (by predicted IoU) and the stable ones (masks whose shape barely changes when the probability threshold moves). Non-maximum suppression removes duplicates, and zoomed-in crops improve small masks. This stage ran on all 11M images and produced 1.1B masks, 99.1% of the total.

The authors checked mask quality by asking annotators to correct automatic masks on 500 images, about 50k masks. For 94% of pairs the automatic and corrected masks have an IoU above 0.9. For comparison, the paper cites prior work that estimates inter-annotator consistency at 85 to 91% IoU.

The paper releases SA-1B for research purposes and the model under Apache 2.0. Faces and license plates are blurred. Images are shared at a shortest side of 1500 pixels, although the originals average 3300 by 4950.

Results

The paper evaluates five tasks, four of which differ from training. The most direct test uses a single foreground point, which is the hardest case because it is often ambiguous.

Single point, 23 datasets. Against RITM, a strong interactive segmenter, SAM has higher mean IoU on 16 of the 23 datasets, by up to about 47 IoU points. With an oracle that picks the best of SAM's three masks, SAM beats RITM on all 23. This gap is mostly ambiguity, which automatic metrics punish because ground truth holds one mask per point. The human study, which rates masks from 1 to 10, gives SAM means between 7 and 9. The authors note that on the datasets where SAM loses on automatic metrics, humans rate it higher.

Edge detection (BSDS500). SAM was not trained for edges, and it gets an optimal dataset scale F-score (ODS) of 0.768. This is below HED's 0.788, which was trained on BSDS500, and above the older zero-shot methods such as Canny at 0.600. SAM predicts more edges than the annotators marked, which lifts recall at the cost of precision.

Object proposals (LVIS). The average recall at 1000 proposals is 59.3 for SAM and 63.0 for ViTDet-H, a detector used here as the strongest baseline. SAM is better on rare objects (65.8 against 58.3) and common objects (63.9 against 63.3). The text says SAM also beats ViTDet on medium and large objects. Table 4 shows large objects at 86.9 for SAM and 87.0 for ViTDet, so the large-object result is a tie within rounding, not a win.

Instance segmentation. SAM takes boxes from ViTDet and segments them. Mask AP is lower than ViTDet's, at 46.5 against 51.0 on COCO and 44.7 against 46.6 on LVIS. Human raters prefer SAM's masks, with crisper boundaries. The authors hypothesize that ViTDet does better on the metric because it has learned annotation idiosyncrasies in COCO and LVIS, which a zero-shot model cannot exploit.

Text to mask. During training, SAM receives CLIP image embeddings of masks, and at inference it receives CLIP text embeddings. The paper shows qualitative examples such as "a wheel", and it reports failures where a second point fixes the prediction. There are no quantitative numbers.

Ablations. Each data engine stage improves mean IoU on the 23-dataset suite, and automatic-only training is about 0.5 mIoU below all-stage training, which is why the authors use it by default. Training on 1M images, about 10% of SA-1B, is comparable to the full set, which the authors call a practical setting. Scaling the image encoder from ViT-B to ViT-H helps substantially, while ViT-L to ViT-H is only a marginal gain.

Why it mattered

The paper's stated contributions are the task, the model and the dataset. The authors say they hope SA-1B becomes a valuable resource for building new foundation models, and they release the model and data. They are careful to say whether SAM counts as a foundation model "remains to be seen by how it is used in the community". This lesson does not claim how it was used.

The authors' own limits are specific. SAM can miss fine structures, hallucinates small disconnected components, and does not produce boundaries as crisp as slower methods that zoom in. It is not the best choice when many interactive clicks are available. Although the decoder runs in real time, the overall system is not real time with the heavy encoder. The text-to-mask result is exploratory. And the authors say it is unclear how to write simple prompts for semantic and panoptic segmentation.

The paper also reports a fairness analysis of geographic and income coverage in SA-1B, and says that SAM performs similarly across the groups of people it measured. It notes that Africa, Latin America and the Caribbean, and low-income countries are under-represented across the datasets it compares.

Reading guide

Read the paper in this order. Prerequisites are listed where they first matter.

  1. Section 1 and 2 (introduction and task). Needs Zero-Shot Learning for the transfer idea, Image Segmentation for what a mask is, and CLIP for the promptable analogy with language models.
  2. Section 3 (model). Needs Vision Transformer (ViT) for the image encoder and ViT for its design, Masked Autoencoder for the MAE pre-training, Positional Encoding for the point and box encodings, and Encoder-Decoder Architecture for the decoder's cross-attention in both directions. The decoder block is a Transformer block with a change.
  3. Section 3, the loss and the training paragraph. Needs Cross-Entropy Loss as the nearest background for a per-pixel mask loss, and Gradient Descent for the minimum-over-masks idea.
  4. Section 4 (data engine). Needs Self-Supervised Learning for the contrast the paper draws, and Masked Autoencoders Are Scalable Vision Learners (MAE) for the pre-training it inherits.
  5. Section 7 (experiments). Needs Contrastive Learning for the CLIP text-image alignment behind the text prompts.

Check yourself

QuestionWhy does SAM predict three masks for each prompt rather than one, and why does the training loss use only the minimum over the three?Show answer

A single prompt, such as a point on a shirt, can be valid for a part, the whole, or a larger object. A single output averages these, which gives a poor mask. Three outputs cover the nested levels, which the authors found sufficient because nesting is at most about three deep. Taking the minimum loss means only the best-matching output receives gradient on each example, so the outputs specialize instead of averaging.

QuestionIn the data engine, the average annotation time falls from 34 to 14 seconds per mask and the masks per image rise from 20 to 44 during stage one. What do these numbers suggest about the model's role?Show answer

As the model improves, it does more of the work: each click or correction is quicker, so annotators label more objects per image in the same time. The fall in time and the rise in masks per image together show that model assistance speeds annotation, which is why the authors retrain the model after each batch of new masks.

QuestionSAM is evaluated on LVIS object proposals with AR at 1000. Explain why SAM can beat ViTDet on rare objects but still lose overall, using Table 4.Show answer

Table 4 gives SAM 65.8 on rare objects against 58.3 for ViTDet, but 59.3 overall against 63.0. ViTDet was trained on LVIS, so it can learn LVIS-specific annotation biases, which helps it on frequent objects (63.1 against 59.1 for SAM). SAM, trained without LVIS, does better on rare and common categories but loses on frequent ones, and the overall average includes the frequent categories.

QuestionSAM gets 16 of 23 datasets higher than RITM on single-point mIoU, and all 23 with an oracle. What does the oracle result tell you about where the gap comes from?Show answer

The oracle picks the most relevant of SAM's three masks by comparing with ground truth, so it removes the ambiguity penalty. Because SAM beats RITM on all 23 with the oracle, the shortfall on some datasets comes from ambiguity: SAM's top-ranked mask sometimes differs from the annotators' single mask for that point, rather than from SAM's masks being worse.

Sources

Read the full paper

Alexander Kirillov, Eric Mintun, Nikhila Ravi et al., 2023. arXiv:2304.02643