Foundations to Frontier
Tests
E. Deep Learning › E10 Segmentation Architectures

Segment Anything (SAM)

The Segment Anything Model (Kirillov and colleagues, ICCV 2023) is a promptable segmenter: given an image and a prompt (points, a box or a rough mask), it returns a valid mask for whatever the prompt points at, even for objects and domains it never saw. It pairs a heavy ViT image encoder, run once per image, with a light prompt encoder and mask decoder that run in about 50 ms. It was trained on SA-1B (11 million images, 1.1 billion masks) collected with a model-in-the-loop data engine. For ambiguous prompts it predicts three masks and trains only the best one. This page covers the promptable task, the architecture, the data engine and ambiguity. In the exercises you implement SAM's preprocessing, prompt encoding and loss, then show that one output learns the 'middle' answer to an ambiguous click, while minimum-loss training recovers part, subpart and whole, but only when the outputs start out different.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Click, and get a mask

Click on anything in a photo, a dog, its ear or a cloud, and SAM outlines it. You can also drag a box or click several points to say “this, not that”. SAM was trained on over a billion masks, so it works on images it has never seen.

A click can be ambiguous: did you mean the shirt’s pocket, the shirt or the person? SAM returns three answers (small, medium, large) with a confidence score for each. The demo shows how a mask is scored against the intended one.

Segmentation lab
pixel accuracy 0.893 · IoU 0.509 · Dice 0.675 (blue: correct, red: false positive, yellow: missed)
Segmentation labels every pixel. Coarse score maps lose boundaries when upsampled; skip connections from finer layers (FCN, U-Net) and dilated convolutions (DeepLab) recover detail. Judge masks by IoU or Dice, not pixel accuracy, which background inflates.
Why engineers care

Promptable segmentation speeds up labelling enormously and lets robots and analysts segment new kinds of objects (debris, crops, damaged parts) without retraining.

📝 Quick check (Level 0)
0/3 answered
  1. 1. SAM's input besides the image:
  2. 2. For an ambiguous click SAM returns…
  3. 3. SAM's training set has about…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Preprocessing:
    • resize the longer side to 1024 and pad to 1024 × 1024 (a 480 × 640 image becomes 768 × 1024);
    • prompts are scaled the same way, so the point (320, 240) becomes (512, 384).
  • Image encoder:
    • an MAE-pretrained ViT (ViT-H: 632 M parameters) with 16 × 16 patches gives a 64 × 64 × 256 embedding;
    • it runs once per image (about 0.15 s on a datacentre GPU).
  • Prompt encoder:
    • points and box corners become random Fourier positional encodings (256 numbers each) plus learned type embeddings (foreground, background, corner);
    • rough masks are downsampled by convolutions and added to the image embedding.
  • Mask decoder:
    • a two-layer two-way transformer: tokens attend to the image and the image attends to tokens;
    • it outputs 3 masks (upsampled 4× to 256 × 256) and an IoU estimate for each;
    • with several prompts, which are less ambiguous, a separate single output is used.
  • Loss:
    • 20 × focal + 1 × dice on the mask, plus mean squared error on the IoU estimate;
    • with 3 outputs, only the lowest mask loss is backpropagated.
  • SA-1B: 1.1 billion masks over 11 million images, about 100 per image.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Image embedding grid for a 1024 input and 16-pixel patches:
  2. 2. Focal to dice weight in SAM's loss:
  3. 3. Masks per image in SA-1B:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

SAM in code

Exercise 1.

  • Preprocessing gave 768 × 1024 for a 480 × 640 image.
  • The Fourier encoding of the image centre was sin 0 and cos 1 for every frequency (a 256-number vector).
  • The loss for logits [0, 0] and targets [1, 0] was 20 · 0.0866 + 0.333 = 2.07 (with focal α = 0.25, γ = 2).

Practice.

  • The segment_anything package provides:
    • SamPredictor for prompts: call set_image once, then predict per prompt;
    • SamAutomaticMaskGenerator, which prompts a 32 × 32 grid of points and filters masks by predicted IoU (≥ 0.88) and stability score (≥ 0.95), then NMS.
  • Stability score: the IoU between the mask thresholded at logit +1 and at −1. A mask that barely changes is reliable.
  • Lighter variants: MobileSAM, EfficientSAM and SAM 2’s Hiera encoders cut the cost of the image encoder. SAM 2 (2024) adds a memory for video.
from segment_anything import sam_model_registry, SamPredictor
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h.pth"); pred = SamPredictor(sam)
pred.set_image(image)                                         # heavy encoder, once per image
masks, scores, logits = pred.predict(point_coords=np.array([[x, y]]), point_labels=np.array([1]), multimask_output=True)
best = masks[scores.argmax()]                                 # pick by predicted IoU
🐍 Exercise 1: preprocessing, prompts and loss
Implement SAM's resize, prompt transform, random Fourier positional encoding and the 20:1 focal–dice loss.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Automatic mask generation prompts…
  2. 2. The stability score compares masks thresholded at…
  3. 3. SAM 2 adds…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

The promptable task.

  • SAM’s goal is a valid mask for any prompt: for an ambiguous prompt, any one of the plausible objects is acceptable.
  • This task is general enough to pretrain on and to adapt by prompting to downstream problems:
    • edge detection;
    • object proposals;
    • instance segmentation with a detector’s boxes as prompts.

Ambiguity and the minimum loss.

  • If one output is trained on all plausible answers to the same prompt, it converges to a compromise. Under per-pixel cross-entropy, that is the pixel-wise average.
  • With three outputs and only the best one trained per example (multiple-choice learning), each output can specialise to one answer.
  • Exercise 2 shows this works only if the outputs differ at the start; otherwise one output wins every example and the others stay unused.
  • In SAM the outputs are separate learned tokens.

Data engine. SA-1B was built in three stages:

  1. Annotators corrected SAM’s masks (assisted-manual).
  2. SAM proposed confident masks and annotators added the missing ones (semi-automatic).
  3. SAM prompted with a grid generated masks with no annotator (fully automatic). 99.1% of SA-1B’s masks came from this stage.
📝 Quick check (Level 3)
0/3 answered
  1. 1. One output trained on several valid answers converges to…
  2. 2. Most SA-1B masks came from…
  3. 3. Minimum-loss training risks…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How should an ambiguous click be trained?

History.

  • A. Kirillov, E. Mintun, N. Ravi, H. Mao, C. Rolland, L. Gustafson, T. Xiao, S. Whitehead, A. Berg, W.-Y. Lo, P. Dollár and R. Girshick introduced SAM and SA-1B (ICCV 2023). They evaluated zero-shot transfer on 23 datasets.
  • Multiple-choice learning, which trains several outputs with a minimum loss, goes back to A. Guzman-Rivera, D. Batra and P. Kohli (NeurIPS 2012).
  • SAM 2 (N. Ravi et al., 2024) extended promptable segmentation to video.

Exercise 2. A click at the centre has three valid answers: a subpart, a part containing it, and the whole object containing both (nested 32 × 32 masks). We train free mask logits on randomly drawn answers (1500 steps) four ways and report the best IoU any output achieves with each answer (seed 0):

training subpart part whole uses per output
1 output 0.250 1.000 0.338
3 outputs, each trained on every answer 0.250 1.000 0.338
3 outputs, minimum loss, random start 0.250 1.000 1.000 1055, 445, 0
3 outputs, minimum loss, spread start 1.000 1.000 1.000 504, 503, 493
  • One output learns the middle answer.
    • The per-pixel average exceeds 0.5 exactly where two of the three nested answers agree, which is the part.
    • So a single-output model always returns the part, never the subpart or the whole.
    • Training three outputs on every answer just gives three copies.
  • Minimum loss can separate the answers but can also collapse.
    • From a near-zero random start, one output stays unused in all 10 seeds tried, and all three answers were never found.
    • When the outputs start as faint blobs of different sizes (a stand-in for SAM’s distinct output tokens), all three answers were found in 10 of 10 seeds.
    • At half that starting strength, they were found in 8 of 10.
  • These are free logits, not a network. SAM also has a predicted-IoU head to choose among its outputs at test time.
🐍 Exercise 2 (research): how should an ambiguous click be trained?
Train one or three mask outputs on nested valid answers with averaged or minimum loss and compare which answers they recover.

SAM in AI, robotics and aerospace

  • Annotation: SAM-assisted labelling tools cut mask annotation time for new datasets (crops, defects, satellite objects).
  • Robotics: prompting SAM with detector boxes or gaze points gives masks for grasping unfamiliar objects.
  • Remote sensing and science: SAM variants are adapted for aerial imagery, microscopy and medical scans, though domain shift often needs fine-tuning.

References

  1. A. Kirillov et al. (2023). “Segment anything.” Proc. ICCV.
  2. N. Ravi et al. (2024). “SAM 2: segment anything in images and videos.” arXiv:2408.00714.
  3. A. Guzman-Rivera, D. Batra, P. Kohli (2012). “Multiple choice learning: learning to produce multiple structured outputs.” Proc. NeurIPS.