TAI BUI
Back to curriculum
BuildPython

SAM 3 & Open-Vocabulary Segmentation

Give a model a text prompt and an image and get a mask for every object that matches. SAM 3 does it in one forward pass, no separate detector.

TIME: ~60 minutesPREREQUISITES: Phase 4 Lesson 07 (U-Net), Phase 4 Lesson 08 (Mask R-CNN), Phase 4 Lesson 18 (CLIP)

Learning Objectives

  • Distinguish SAM (visual prompts only), Grounded SAM / SAM 2 (detector + SAM), and SAM 3 (native text prompts via Promptable Concept Segmentation)
  • Explain the SAM 3 architecture: shared backbone + image detector + memory-based video tracker + presence head + decoupled detector-tracker design
  • Use Hugging Face `transformers` SAM 3 integration for text-prompted detection, segmentation, and video tracking
  • Pick between SAM 3, Grounded SAM 2, YOLO-World, and SAM-MI based on latency, concept complexity, and deployment target

The Problem

The 2023 SAM was a visual-prompt-only model: click a point or draw a box and it returns a mask. Ask for "every orange in this photo" and SAM alone can't do it. You needed a detector (Grounding DINO) to produce boxes first, then SAM to segment each one. Grounded SAM turned that into a working pipeline, but it was still a cascade of two frozen models, and cascades accumulate error at every hop.

SAM 3 (Meta, Nov 2025, ICLR 2026) collapsed the cascade. Give it a short noun phrase or an image exemplar as a prompt and it returns every matching mask and instance ID in one forward pass. That's Promptable Concept Segmentation (PCS). The March 2026 Object Multiplex update (SAM 3.1) extends this to video, tracking multiple instances of the same concept efficiently across frames.

The bigger change is structural: 2D segmentation, detection, and text-image grounding have merged into one model. The production question isn't "which pipeline do I chain together" anymore. It's "which promptable model handles my use case end to end."

Warm-up0/3
1. What does a segmentation mask give you that a bounding box does not?Warm-up
One blob-shaped object inside a dashed rectangle labelled bounding box, beside a dashed question-mark box asking what a mask gives you for this object.
A bounding box around one object, with what a mask gives you left open.
2. What does CLIP learn to do with images and text?Warm-up
An image icon and a caption card reading 'a photo of a dog', both with arrows leading to a dashed question-mark box asking what CLIP does with both.
An image and its caption, with what CLIP does with the pair left open.
3. A photo contains three cars. Which kind of output gives each car its own separate mask?Warm-up
Three car icons labelled Car A, Car B and Car C inside one dashed photo frame, with an arrow to a dashed question-mark box asking about the output for 3 masks.
One photo with three cars, the kind of output that would give each its own mask left open.
Check: The Problem0/1
1. Before SAM 3, why did text-prompted segmentation mean chaining a separate detector into SAM instead of using SAM alone?Explain
A text query card reading 'the red car' feeding a Grounding DINO detector box, which feeds a 2023 SAM box that outputs a mask, above a dashed question-mark box asking why the detector step is needed.
The pre-SAM 3 chain for a text query, with why the detector step is needed left open.

The Concept

The three generations

Mermaid diagram

Promptable Concept Segmentation

A "concept prompt" is a short noun phrase ("yellow school bus", "striped red umbrella", "hand holding a mug") or an image exemplar. The model returns segmentation masks for every instance in the image that matches the concept, plus a unique instance ID per match.

This differs from classic visual-prompt SAM in three ways:

  1. No per-instance prompting required: one text prompt returns all matches.
  2. Open-vocabulary: the concept can be anything describable in natural language.
  3. Returns multiple instances at once rather than one mask per prompt.

Key architectural pieces

  • Shared backbone: a single ViT (Vision Transformer) processes the image. Both the detector head and the memory-based tracker read from it.
  • Presence head: predicts whether the concept is present in the image at all, decoupling "is this here?" from "where is it?" and cutting false positives on absent concepts.
  • Decoupled detector-tracker: image-level detection and video-level tracking have separate heads so they don't interfere with each other.
  • Memory bank: stores per-instance features across frames for video tracking (the same mechanism SAM 2 used).

Those four pieces run on every forward pass. What taught them to work is a data pipeline built at a different scale entirely.

Training at scale

SAM 3 was trained on 4 million unique concepts generated by a data engine that iteratively annotates and corrects using AI plus human review. The new SA-CO benchmark contains 270K unique concepts, 50x larger than prior benchmarks. SAM 3 reaches 75-80% of human performance on SA-CO and doubles existing systems on image and video PCS.

SAM 3.1 Object Multiplex

March 2026 update: Object Multiplex introduces a shared-memory mechanism for joint tracking of many instances of the same concept at once. Previously, tracking N instances meant N separate memory banks. Multiplex collapses that into one shared memory with per-instance queries, so tracking stays fast as the object count grows, without giving up accuracy.

Where Grounded SAM still matters in 2026

  • When you need a specific open-vocabulary detector swapped in (DINO-X, Florence-2).
  • When the SAM 3 license (gated on HF) is a blocker.
  • When you need more control over the detector threshold than SAM 3 exposes.
  • For research or ablation work on the detector component.

Modular pipelines still have a place. For most production work, SAM 3 is the simpler answer.

YOLO-World vs SAM 3

  • YOLO-World: open-vocabulary detector only, no masks. Real-time. Best when you need boxes at high fps.
  • SAM 3: full segmentation plus tracking. Slower, but richer output.

Production split: YOLO-World for fast detection-only pipelines (robotics navigation, fast dashboards), SAM 3 for anything that needs masks or tracking.

SAM-MI efficiency

SAM-MI (2025-2026) addresses SAM's decoder bottleneck. Key ideas:

  • Sparse point prompting: uses a few well-chosen points instead of dense prompts, cutting decoder calls by 96%.
  • Shallow mask aggregation: merges rough mask predictions into one sharper mask.
  • Decoupled mask injection: decoder receives pre-computed mask features instead of re-running.

Net effect: roughly 1.6x speedup over Grounded-SAM on open-vocabulary benchmarks.

Output format for the three models

All three return the same general structure: boxes, labels, scores, masks, IDs. That's deliberate, so your downstream pipeline doesn't have to branch on which model produced the output.

Check: The Concept0/22
1. What is Promptable Concept Segmentation (PCS), introduced by SAM 3?Define
A concept prompt card reading 'yellow school bus' and a street photo both feeding a SAM 3 box, with an arrow to a dashed question-mark box asking what comes back.
A concept prompt and a photo feeding SAM 3, with what comes back left open.
2. SAM 3's presence head produces what?Define
A shared ViT backbone box with an arrow into a highlighted presence head box, then an arrow to a dashed question-mark box asking what it produces.
The presence head's position in SAM 3, reading off the shared backbone, with its output left open.
3. What is open-vocabulary segmentation?Define
A user query card reading 'striped red umbrella' and a street photo feeding a model box, with an arrow to a dashed question-mark box asking how the target is chosen.
A user's typed query and a photo going into a model, with how the target is chosen left open.
4. What counts as a concept prompt for SAM 3?Define
A dashed question-mark slot labelled concept prompt feeding a SAM 3 box, which feeds a masks box, with what counts as a concept prompt left open.
SAM 3's concept-prompt slot, with what can fill it left open.
5. What is SA-CO?Define
A data engine box feeding a SAM 3 box under the heading the lesson's SAM 3 training setup, with a separate dashed question-mark box asking what SA-CO is and how big it is.
The lesson's SAM 3 training setup, with SA-CO's own identity and size left open.
6. What is Object Multiplex in SAM 3.1?Define
A timeline with SAM in 2023, SAM 3 in November 2025 and a highlighted SAM 3.1 in March 2026, with a dashed question-mark box under SAM 3.1 asking what Object Multiplex does.
Where SAM 3.1 sits in the lesson's timeline, with what Object Multiplex does left open.
7. What is Grounded SAM 2?Define
A user query card reading 'the red car' with an arrow into a dashed box named Grounded SAM 2 holding a question mark, asking what kind of system it is.
A text query arriving at Grounded SAM 2, with what kind of system it is left open.
8. What is SAM-MI aimed at?Define
A card naming SAM-MI, Mask Injection from 2025 to 2026, as one of the lesson's open-vocabulary options, beside a dashed question-mark box asking what it is aimed at.
SAM-MI's name and date, with what it is aimed at left open.
9. What does the memory bank store in SAM 3's video tracking?Define
Three video frames in sequence with an arrow into a memory bank box, above a dashed question-mark box asking what it stores.
Three frames of a clip feeding the memory bank, with what it stores left open.
10. SAM 3 was trained on a data engine covering how many unique concepts, and what score does it reach on the SA-CO benchmark relative to human performance?Define
A data engine box above a dashed question-mark box asking how many concepts, beside a SA-CO benchmark box above a dashed question-mark box asking the score versus human performance.
The training data engine and the separate SA-CO benchmark, with the training concept count and the human-performance score both left open.
11. Why keep a decoupled detector + SAM 2 pipeline (Grounded SAM 2) in 2026 if SAM 3 already does text-prompted segmentation?Explain
A SAM 3 box noted as doing text-prompted segmentation beside a Grounded SAM 2 box that some teams still reach for, above a dashed question-mark box asking what keeping it buys them.
Both options still on the table in 2026, with what keeping the older one buys you left open.
12. Which of these is a way PCS differs from classic visual-prompt SAM?Explain
A box reading classic SAM, visual prompts, beside a PCS card with the concept prompt 'yellow school bus' and an arrow down into a dashed question-mark box asking how PCS differs.
Classic SAM's visual prompts next to a PCS concept prompt, with how PCS differs left open.
13. Why does SAM 3 give image-level detection and video-level tracking separate heads instead of one shared head for both?Explain
Two cards side by side, image-level detection on one still image and video-level tracking across frames, above a dashed question-mark box asking why each gets its own head.
The two jobs SAM 3 runs, with why each gets its own head left open.
14. SAM 3.1 Object Multiplex (March 2026) introduced a shared-memory mechanism for tracking. What does it replace?Explain
An Object Multiplex box marked shared-memory tracking under the heading SAM 3.1, March 2026, with an arrow down to a dashed question-mark box asking what it replaces.
SAM 3.1's Object Multiplex mechanism, with what it replaces left open.
15. SAM-MI addresses SAM's decoder bottleneck. Which technique does the lesson credit with cutting decoder calls by 96%?Explain
Two bars for decoder calls on one image, the second 96 percent shorter and marked SAM-MI, above a dashed question-mark box asking which SAM-MI technique does this.
The 96 percent cut in decoder calls drawn to scale, with which technique produces it left open.
16. What problem does SAM 3's presence head solve?Explain
SAM 3's detector head, tracker head and a highlighted presence head in a row, with an arrow down from the presence head to a dashed question-mark box asking which failure mode it targets.
The presence head among SAM 3's heads, with the failure mode it targets left open.
17. A pipeline needs open-vocabulary boxes at high fps and never uses masks. Which model family does the lesson recommend?Apply
A card listing a pipeline's needs, open-vocabulary boxes, high fps and never uses masks, beside a dashed question-mark box asking the model family.
A pipeline's stated needs, boxes only at high fps, with the model family to pick left open.
18. A team must test a Florence-2 detector in their open-vocabulary pipeline and keep SAM-style masks. Which stack fits?Apply
A card listing two requirements, test a Florence-2 detector and keep SAM-style masks, beside a dashed question-mark box asking which stack fits.
A team's two stated requirements, with which stack fits them left open.
19. You prompt a detector-plus-SAM cascade with "zebra" on a street photo with no zebras and still get a confident mask. Which SAM 3 piece is designed to prevent this?Analyze
A street photo holding a car and two plain blocks for other street objects but no zebra, a prompt card reading zebra, and a dashed question-mark box asking what catches this, with a note that the cascade still returns a confident mask.
A street scene with no zebra, prompted with 'zebra', with which SAM 3 piece would catch the false mask left open.
20. A video tracker keeps a separate memory bank for each of 40 tracked instances and slows down as the crowd grows. Which change addresses the cause?Analyze
A card stating the tracker keeps 40 tracked instances with one separate memory bank each and slows down as the crowd grows, above a dashed question-mark box asking which change fixes the cause.
A tracker with 40 separate per-instance memory banks slowing down, with the fix left open.
21. A team commits its roadmap to SAM 3, but legal will not accept the terms of the gated Hugging Face access. What did the plan miss, and what fits?Analyze
A roadmap box committed to SAM 3 next to a padlock icon with the note legal rejects gated HF terms, and a dashed question-mark box asking what fits instead.
A roadmap blocked by SAM 3's gated license, with what fits instead left open.
22. A robot's navigation loop needs text-described boxes at high fps, while an offline annotation tool needs masks of every matching instance. Which split fits?Design
A card for the robot navigation loop needing text-described boxes at high fps, and a card for an offline annotation tool needing masks of every instance, above a dashed question-mark box asking which system for each.
Two different jobs, boxes at high fps versus masks offline, with which system fits each left open.

Build It

Step 1: Prompt construction

Build a helper that turns a user sentence into a list of SAM 3 concept prompts. This is the boundary where "what the user typed" meets "what the model consumes".

python
def split_concepts(sentence):
    """
    Heuristic splitter for multi-concept prompts.
    Returns list of short noun phrases.
    """
    for sep in [",", ";", "and", "or", "&"]:
        if sep in sentence:
            parts = [p.strip() for p in sentence.replace("and ", ",").split(",")]
            return [p for p in parts if p]
    return [sentence.strip()]
 
print(split_concepts("cats, dogs and balloons"))

SAM 3 accepts one concept per forward pass; for multi-concept queries, loop or batch them.

Step 2: Post-processing helpers

Turn SAM 3's raw outputs into a clean list of detections that match our Phase 4 Lesson 16 pipeline contract.

python
from dataclasses import dataclass
from typing import List
 
@dataclass
class ConceptDetection:
    concept: str
    instance_id: int
    box: tuple          # (x1, y1, x2, y2)
    score: float
    mask_rle: str       # run-length encoded
 
 
def rle_encode(binary_mask):
    flat = binary_mask.flatten().astype("uint8")
    runs = []
    prev, count = flat[0], 0
    for v in flat:
        if v == prev:
            count += 1
        else:
            runs.append((int(prev), count))
            prev, count = v, 1
    runs.append((int(prev), count))
    return ";".join(f"{v}x{c}" for v, c in runs)

RLE keeps response payloads small even for many high-resolution masks. The same format works across SAM 2, SAM 3, Grounded SAM 2.

Step 3: A unified open-vocab segmentation interface

Wrap whatever backend you have (SAM 3, Grounded SAM 2, YOLO-World + SAM 2) behind a single method. Your downstream code does not change when the backend does.

python
from abc import ABC, abstractmethod
import numpy as np
 
class OpenVocabSeg(ABC):
    @abstractmethod
    def detect(self, image: np.ndarray, concept: str) -> List[ConceptDetection]:
        ...
 
 
class StubOpenVocabSeg(OpenVocabSeg):
    """
    Deterministic stub used for pipeline testing when real models are not loaded.
    """
    def detect(self, image, concept):
        h, w = image.shape[:2]
        return [
            ConceptDetection(
                concept=concept,
                instance_id=0,
                box=(w * 0.2, h * 0.3, w * 0.5, h * 0.8),
                score=0.89,
                mask_rle="0x100;1x50;0x200",
            ),
            ConceptDetection(
                concept=concept,
                instance_id=1,
                box=(w * 0.55, h * 0.25, w * 0.85, h * 0.75),
                score=0.74,
                mask_rle="0x80;1x40;0x220",
            ),
        ]

The real SAM3OpenVocabSeg subclass would wrap transformers.Sam3Model and Sam3Processor.

Step 4: Hugging Face SAM 3 usage (reference)

Here's the real model, via the transformers integration:

python
from transformers import Sam3Processor, Sam3Model
import torch
 
processor = Sam3Processor.from_pretrained("facebook/sam3")
model = Sam3Model.from_pretrained("facebook/sam3").eval()
 
inputs = processor(images=pil_image, return_tensors="pt")
inputs = processor.set_text_prompt(inputs, "yellow school bus")
 
with torch.no_grad():
    outputs = model(**inputs)
 
masks = processor.post_process_masks(
    outputs.masks, inputs.original_sizes, inputs.reshaped_input_sizes
)
boxes = outputs.boxes
scores = outputs.scores

One prompt, all matches returned in a single call. Feed the same model a sequence of frames instead of a single image and the memory bank persists each instance's features across them automatically; that's the mechanism behind the video-tracking use cases in Use It.

Step 5: What you gain and give up moving off Grounded SAM 2

An honest benchmark: what happens when you replace Grounded SAM 2 with SAM 3 in a real pipeline?

  • Latency: SAM 3 saves one forward pass (no separate detector) but the model itself is heavier; usually net-neutral or a slight speedup.
  • Accuracy: SAM 3 substantially better on rare or compositional concepts ("striped red umbrella"). Similar on common single-word concepts.
  • Flexibility: Grounded SAM 2 lets you swap detectors (DINO-X, Florence-2, Grounding DINO 1.5); SAM 3 is monolithic.

Conclusion: SAM 3 is the default for 2026 open-vocab seg. Grounded SAM 2 is still the right answer when you need detector flexibility or different license terms.

Check: Build It0/10
1. Why does the lesson's `OpenVocabSeg` abstract base class wrap SAM 3, Grounded SAM 2, and YOLO-World+SAM 2 behind the same `detect()` method returning `ConceptDetection` objects?Explain
Three backend boxes, SAM 3, Grounded SAM 2 and YOLO-World plus SAM 2, all feeding one detect(image, concept) box that outputs ConceptDetection, above a dashed question-mark box asking why one shared interface.
Three backends behind one detect() method producing ConceptDetection objects, with why that design is used left open.
2. Moving from Grounded SAM 2 to SAM 3 drops the separate detector pass, yet latency is usually net-neutral. Why?Explain
A detector pass and a segmentation pass under Grounded SAM 2, two passes, beside a single SAM 3 one-pass box, above a dashed question-mark box asking the net latency difference and why.
Grounded SAM 2's two forward passes next to SAM 3's one pass, with the net latency difference and its cause left open.
3. The lesson's `split_concepts` first sees a comma in the sentence, replaces "and " with ",", splits on commas, strips each piece and drops empties. What does `split_concepts("cats, dogs and balloons")` return?Apply
A code box showing the lesson's split_concepts pseudocode, an input box reading 'cats, dogs and balloons', and a dashed question-mark box asking the return value.
The lesson's own split_concepts pseudocode applied to one input, with the returned list left open.
4. `split_concepts` replaces "and " with "," and then splits only on commas, even though it also checks for ";" in the sentence. What does `split_concepts("dogs; cats")` return?Apply
The same split_concepts pseudocode box, an input box reading 'dogs; cats', and a dashed question-mark box asking the return value.
The lesson's own split_concepts pseudocode applied to a semicolon-separated input, with the returned list left open.
5. `rle_encode` joins (value, count) runs as `value x count`, separated by semicolons. What does it return for a flattened binary mask [0, 0, 0, 1, 1, 0]?Apply
An rle_encode code box, a strip of six cells reading 0, 0, 0, 1, 1, 0, and a dashed question-mark box asking the RLE string.
The rle_encode pseudocode applied to a six-cell mask, with the encoded string left open.
6. `StubOpenVocabSeg.detect` builds the first box as (w*0.2, h*0.3, w*0.5, h*0.8), with h, w taken from `image.shape[:2]`. For an image of shape (100, 200, 3), what is the first box?Apply
A code box with the stub detector's box formula and an input reading image.shape equals 100, 200, 3, with a dashed question-mark box asking the first box.
The stub detector's box formula with a given image shape, the resulting box left open.
7. In the Hugging Face `transformers` SAM 3 integration, what does `processor.set_text_prompt(inputs, ...)` do before the model's forward pass?Apply
A code box with two lines, processor building inputs then set_text_prompt highlighted, above a dashed question-mark box asking what this line does before the forward pass.
The Hugging Face SAM 3 integration's set_text_prompt line highlighted, with what it does left open.
8. A team replaces Grounded SAM 2 with SAM 3 and sees little accuracy gain on "car" and "person". Which explanation fits the lesson?Analyze
A card listing the swap test concepts car and person under the heading Grounded SAM 2 to SAM 3, with a dashed question-mark box asking why there is so little accuracy gain.
A model swap checked on the concepts car and person, with why the accuracy gain is small left open.
9. A user types "cats, dogs and balloons" and SAM 3 takes one concept per forward pass. Which design handles the query?Design
A card reading the user's input, cats, dogs and balloons, with a note that SAM 3 takes one concept per forward pass, and a dashed question-mark box asking which design handles this.
A multi-concept user query against SAM 3's one-concept-per-pass limit, with the handling design left open.
10. Your service runs SAM 3 today but may need to move to Grounded SAM 2 if licensing blocks it. Which design keeps downstream code unchanged?Design
A SAM 3 today box that may move to a Grounded SAM 2 box if licensing blocks it, above a dashed question-mark box asking which design keeps callers unchanged.
A service that may need to swap backends, with the design that keeps downstream code unchanged left open.

Use It

Production deployment patterns:

  • Real-time annotation: SAM 3 plus CVAT's label-as-text-prompt feature. Annotators select a label name, SAM 3 pre-labels every matching instance, and a human reviews and corrects.
  • Video analytics: SAM 3.1 Object Multiplex for multi-object tracking, feeding frames to the memory-based tracker.
  • Robotics: SAM 3 for open-vocab manipulation ("pick up the red cup"), running as a planning primitive.
  • Medical imaging: SAM 3 fine-tuned on medical concepts, which requires an access request on HF.

Ultralytics wraps SAM 3 in its Python package:

python
from ultralytics import SAM
 
model = SAM("sam3.pt")
results = model(image_path, prompts="yellow school bus")

Same interface as YOLO and SAM 2.

Check: Use It0/1
1. Which production deployment pattern does the lesson pair with SAM 3 for real-time annotation workflows?Define
A card describing the lesson's real-time annotation workflow, where an annotator selects a label name and a human reviews and corrects what comes back, above a dashed question-mark box asking which deployment pattern this is.
The annotation workflow's human steps, with which named deployment pattern it is left open.

Ship It

This lesson produces:

  • outputs/prompt-open-vocab-stack-picker.md: a prompt that picks SAM 3 / Grounded SAM 2 / YOLO-World / SAM-MI based on latency, concept complexity, and licensing.
  • outputs/skill-concept-prompt-designer.md: a skill that turns user utterances into well-formed SAM 3 concept prompts (splitting, disambiguation, fallbacks).
Author's Note

I've watched this exact move happen three times now: two-stage detectors collapsing into one-stage, retrieval-plus-rerank collapsing into a single dense retriever, and now detector-plus-SAM collapsing into SAM 3. The lesson repeats: a cascade of frozen models is a scaffold, not a permanent architecture. Train a big enough model on enough paired data and the scaffold usually comes down.

What doesn't disappear is the reason you built the scaffold in the first place. If you needed a specific detector for legal or domain reasons, that need doesn't vanish just because SAM 3 exists — it just moves the question from "how do I glue these two models together" to "is the monolithic model even available to me." SAM 3's gated HF license is a real, boring, non-technical reason teams still reach for Grounded SAM 2 in 2026. Check that box before you commit a roadmap to the newer model.

Exercises

  1. (Easy) Run SAM 3 on 10 images with concept prompts you choose. Compare against SAM 2 + Grounding DINO 1.5 on the same images. Report which concepts each model missed.
  2. (Medium) Build a "click-to-include / click-to-exclude" UI on top of SAM 3: a text prompt returns candidate instances; user clicks keep which ones count as positive. Output the final concept set as JSON.
  3. (Hard) Fine-tune SAM 3 on a custom concept set (e.g. 5 types of electronic components) with 20 labelled images each. Compare to zero-shot SAM 3 on the same test set; measure mask IoU improvement.

Key Terms

TermWhat people sayWhat it actually means
Open-vocabulary segmentation"Segment by text"Produce masks for objects described in natural language, not a fixed label set
PCS"Promptable Concept Segmentation"SAM 3's signature task: given a noun phrase or image exemplar, segment every matching instance
Concept prompt"The text input"Short noun phrase or image exemplar; not a full sentence
Presence head"Is it here?"SAM 3 module that decides whether the concept exists in the image before localisation
SA-CO"SAM 3 benchmark"270K-concept open-vocabulary segmentation benchmark; 50x larger than prior open-vocab benchmarks
Object Multiplex"SAM 3.1 update"Shared-memory multi-object tracking; fast joint tracking of many instances
Grounded SAM 2"Modular pipeline"Detector + SAM 2 cascade; still relevant when detector swap matters
SAM-MI"Efficient SAM variant"Mask Injection for 1.6x speedup over Grounded-SAM

Further Reading