Sub topic 1
What promptable segmentation means
Overview
Most segmentation models are trained for a fixed label set. A street-scene model knows "road", "car" and "pedestrian" and nothing else. The Segment Anything Model (SAM) takes a different approach. It is trained to answer one question: given an image and a hint about where to look, which pixels belong to that thing?
This chapter defines that task, shows how it differs from tasks you already know, and explains why it lets one model work on images it was never trained for. Later chapters cover the architecture and the code in detail.
Prerequisites
This chapter assumes you have:
- Basic Python and NumPy. You can index arrays and read boolean masks.
- Familiarity with PyTorch tensors and loading pretrained checkpoints.
- An understanding of how image segmentation differs from classification and detection.
- A basic idea of Vision Transformers and attention.
You do not need to have used SAM before.
From fixed labels to a promptable task
In a standard segmentation setup, the label set is fixed when you train the model. This table compares the usual tasks with the promptable one.
| Task | Input | Output | Needs class labels |
|---|---|---|---|
| Semantic segmentation | Image | One class per pixel | Yes, fixed set |
| Instance segmentation | Image | One mask per object plus a class | Yes, fixed set |
| Interactive segmentation | Image plus user clicks | Mask refined over many clicks | No |
| Promptable segmentation | Image plus any prompt | At least one valid mask | No |
A prompt is any input that says what to segment. The promptable segmentation task is defined as follows: given an image and any prompt, return a valid mask.
The idea comes from language models. A large language model is pretrained on a broad task, next-token prediction. At use time you steer it with a prompt and it handles tasks it was never explicitly trained on. SAM applies the same recipe to images. The broad pretraining task is "return a valid mask for any prompt". At use time the prompt picks the object.
What "valid" means
"Valid mask" is the part of the definition that matters most. A prompt can be ambiguous. Suppose you click on a person's shirt. You might mean the shirt, the whole person, or the person together with the bag they carry. All three are reasonable.
The task therefore does not demand the single mask you had in mind. It demands that the output be a reasonable mask for at least one object the prompt could refer to. This matters in two ways:
- Training does not punish the model for choosing a sensible interpretation you did not intend.
- The model can return several candidate masks for one prompt, and you choose between them. The chapter on ambiguity covers this in detail.
Without this definition, a single click would be an ill-posed problem. Any fixed answer would be wrong for some users.
How this differs from interactive segmentation
Interactive segmentation is an older task. A user clicks on an object, the model proposes a mask, and the user adds corrective clicks until the mask is good. These systems are judged by how well they do after many clicks.
Promptable segmentation borrows the click-based training idea. During training, SAM's authors simulate a sequence of prompts for each mask. The model is asked for a valid mask after every prompt in the sequence, not only at the end. The difference lies in what is required:
- An interactive system aims for a good mask after enough clicks.
- A promptable model must give a good mask after the first prompt, even an ambiguous one, and then improve as prompts accumulate.
That requirement is what makes the model usable inside other systems. A program can supply a prompt automatically, with no human present, and trust the response.
Prompt types
SAM's design covers four kinds of prompt:
- Points. A foreground point means "this pixel is part of the object". A background point means "this pixel is not".
- Boxes. A rectangle roughly around the object. A box is usually less ambiguous than a single point.
- Masks. A rough or earlier mask that the model refines.
- Text. A free-form description such as "a wheel". The original paper explored this using CLIP, but the released
segment_anythingpackage does not accept text prompts.
Points and boxes are the main inputs in the code you will write. Masks appear as feedback for refinement. A later chapter covers each prompt type in turn.
Why this enables zero-shot transfer
Zero-shot transfer means a model performs a task on data or categories it was not trained on, with no extra training. Promptable segmentation gives SAM this ability for three reasons.
- The task has no class vocabulary. The model learns "what is an object-like region with a boundary", not "what is a dog". Nothing in the output depends on a label set, so a new kind of object does not fall outside the model's vocabulary.
- The prompt is a composable interface. Other components can produce prompts. For example, an object detector can produce boxes, and those boxes become prompts. Gaze points, a user's click, or a grid of points all work. The segmentation model stays unchanged while the prompt source varies. The paper calls this prompt engineering.
- The training data is broad. The model was trained on the SA-1B dataset, which holds over 1 billion masks on about 11 million images. Breadth in the data supports breadth in transfer.
The result is that you can use one checkpoint for photographs, microscope images, or underwater scenes, as long as you can provide a prompt. Quality still varies by domain. The chapter on limitations covers where it breaks down.
The design constraint: real-time prompting
The task definition constrains the architecture. If users click and expect an answer, each prompt must return quickly. But a high-quality image encoder is large and slow.
SAM splits the work into three parts to meet both needs:
- An image encoder runs once per image and produces an image embedding. This is the expensive step.
- A prompt encoder turns points, boxes and masks into vectors. It is cheap.
- A mask decoder combines the two and outputs masks. It is lightweight, so repeated prompting on the same image is fast.
The next chapters examine each part. For now, the point is that the task forces this split. Amortizing the encoder cost across many prompts is what makes interactive use practical.
Seeing the task in code
The official package exposes the task through the SamPredictor class. You give it an image once, then call predict with whatever prompt you have. The example below uses a single foreground point. It assumes you have downloaded the vit_b checkpoint and that the point lies inside your image, so adjust the coordinates to your own photo.
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
sam.to(device="cuda") # use "cpu" if no GPU is available
predictor = SamPredictor(sam)
image = cv2.cvtColor(cv2.imread("photo.jpg"), cv2.COLOR_BGR2RGB)
predictor.set_image(image) # runs the image encoder once
masks, scores, logits = predictor.predict(
point_coords=np.array([[500, 375]]), # (x, y) in pixels
point_labels=np.array([1]), # 1 = foreground, 0 = background
multimask_output=True,
)
print(masks.shape, scores) # (3, H, W) boolean masks and 3 quality scoresNotice what the output does and does not contain:
- It contains three boolean masks and three scores. The scores are the model's own estimate of mask quality, so you can rank the candidates without ground truth.
- It contains no class name. The model tells you where an object is, not what it is.
- Three masks come back for one point because the point is ambiguous. This is the "valid mask" definition at work.
Common misunderstandings
These are the mistakes intermediate readers most often make at this stage.
- Expecting one correct mask per click. The task allows several valid answers. Request multiple masks when the prompt is a single point, then select among them.
- Treating SAM as an instance segmentation model. It does not output classes and does not decide on its own which objects matter. Automatic mask generation, covered later, exists for the "everything" case.
- Assuming that a bigger prompt is always better. A box often resolves ambiguity better than one point, but a poorly placed box can mislead the model. Prompt quality still matters.
- Assuming "zero-shot" means "perfect everywhere". Zero-shot means no retraining. Performance can still fall short in specialized domains, on thin structures, or in low-contrast images.
What comes next
The remaining chapters build on this definition. You will see how each prompt type is encoded, why the image embedding is cached, how the multi-mask output resolves ambiguity, and how to refine a mask using feedback. The final chapters cover automatic mask generation, the data engine that produced SA-1B, the main failure modes, and the extension to video in SAM 2.
Exercises
Exercise
A user clicks once on a mug sitting on a desk. SAM returns three masks: the handle, the mug body, and the mug together with its saucer. Under the promptable segmentation task, is this a failure? Explain.
Show answer
No. The task only requires a valid mask for at least one object the prompt could refer to. A single click is ambiguous, so the model returns several plausible interpretations, and the caller chooses among them, for example by quality score or by adding more prompts.
Exercise
Give two reasons why a promptable model with no class vocabulary can be applied to new image domains without retraining, and name one thing it still cannot do on its own.
Show answer
First, its output is a region, not a category, so unseen object types do not fall outside any label set. Second, the prompt is a composable interface, so any external source (a detector, a user's click, a point grid) can supply it. It cannot tell you what an object is, because the output contains no class names. Pairing it with a classifier or detector is needed for that.
Exercise
How does the promptable task differ from classic interactive segmentation in what the model must deliver after the first prompt?
Show answer
Interactive segmentation judges quality after many corrective clicks. The promptable task requires a valid mask after every prompt in a sequence, including the first, ambiguous one. This lets programs, not only humans, drive the model.