EVERYTHING AIAI engineering, made visual
0/28 complete
LESSON 24 · COMPUTER VISION × AI · USE + BUILD

A click says where.
A concept prompt says what — and returns every one.

The 2023 Segment Anything Model took points and boxes and returned one instance’s mask; there was no text anywhere in it. The production answer became a cascade — a text-conditioned detector, boxes, then SAM — until SAM 3 collapsed it into Promptable Concept Segmentation: a short noun phrase in, every matching instance’s mask and ID out, one forward pass, with a presence head allowed to say the concept is not there. This lesson is the prompt-mode ladder, the shared-backbone architecture behind it, the memory that carries identities through occlusion, the transformers calls, and the arithmetic that decides which stack you should actually ship.

60 MIN · 7 CHAPTERS + CHECKPREREQ · PHASE 4 · LESSONS 07, 08 & 18
FIG. 24 / THE PROMPT LADDER OVER ONE SCENE
concept prompt detector presence vetoed
LESSON 24TYPE · USE + BUILD~60 MINPREREQ · PHASE 4 · LESSONS 07, 08 & 18 (U-NET, MASK R-CNN, CLIP)ORIGINAL LESSON ↗
THE 60-SECOND VERSIONSee the problem ↓
01 / THE PROMPT CHANGED TWICE

Click → text-through-a-detector → text.

SAM (2023) takes a point or a box and returns one instance; the released weights do not take text at all. Grounded SAM 2 (2024) reaches text by running a detector first — text → boxes → one mask per box — and adds video memory. SAM 3 (Nov 2025) takes the short noun phrase directly: Promptable Concept Segmentation returns every matching instance with a mask, an instance ID and a presence score in one forward pass.

1 click → 1 mask · text + detectors → 1 mask per box · 1 concept prompt → every match
02 / ONE BACKBONE, FOUR JOBS

Detector and tracker share the encode.

The paper's architecture is an image-level detector plus a memory-based video tracker over a single backbone, with a presence head decoupling recognition from localisation. The published component sizes: a 32-layer ViT at 1008 px (patch 14 → 72 × 72 = 5,184 tokens), an FPN at 256 channels, a 3-layer geometry encoder for boxes and points, DETR encoder and decoder of 6 layers each with 200 queries, and a mask decoder with 3 upsampling stages.

5,184 tokens · DETR 6 + 6 · 200 queries · memory: 6 recent frames + prompted
03 / THE ENCODE IS THE ECONOMY

Pay the vision pass once; count the rest.

Every stack's biggest bill is the per-image vision encode, so the question is always what happens after the cache. SAM answers a click in ~50 ms once the embedding exists. SAM 3 is 1 vision encode + one concept pass per prompt — all instances included. The cascade pays one mask decode per box. Video pays per object per frame unless multiplexing collapses it.

SAM click ~50 ms · SAM 3 image 30 ms / 100+ objects (H200) · SAM 3.1 16 → 32 FPS (H100) · YOLO-World 19.2 ms (V100, 640²)
MENTAL MODEL IN ONE SENTENCE

A concept prompt is a query, not a label: the model answers “is this here?” with a presence score, “where and how many?” with every matching instance’s mask and ID, and “which one across time?” with a per-instance memory — and each answer costs a pass count you can compute before writing any code.

By the end you will be able to place any 2026 open-vocabulary segmentation task on the prompt-mode ladder and say what it costs: one click against a cached embedding (~50 ms), one vision encode plus one concept pass per prompt for SAM 3, one detector pass plus one mask decode per box for Grounded SAM 2, or boxes only from YOLO-World at 19.2 ms per frame; read SAM 3’s architecture as a shared backbone with a DETR detector, a presence head and an SAM 2-style memory tracker; budget the tracker at 1.05 MB per memory frame per object and decide when SAM 3.1’s Object Multiplex matters; write the transformers calls for text prompts and video tracking with the vision encode cached; and audit an open-vocabulary claim per concept, with its date and hardware attached.

A POINT IS NOT A WORD

SAM knew where.
It had no idea what.

The 2023 Segment Anything Model answers a gesture: click a point, draw a box, get the region. To ask “give me every orange in this photo” you had to bolt on a text-conditioned detector and turn one question into a pipeline. That bolt is the subject of this lesson — and by the end it is gone.

The original SAM is a visual-prompt-only model. Its interface is a click, a box, or a rough mask: something that identifies an object by location. The image encoder turns the photo into embeddings once; a small prompt encoder and mask decoder then answer in about 50 ms per prompt in a browser, which is why clicking feels instant. What no part of that model can do is read the string "yellow school bus" and find every instance. The released weights do not take text at all.

So the field built a cascade. A text-conditioned open-vocabulary detector — Grounding DINO and its descendants — turns the phrase into boxes. SAM turns each box into a mask. Wrap them together and you get Grounded SAM, and after 2024 the video-aware Grounded SAM 2. It works, it ships, and it has a structural cost: two frozen models, one forward pass per prompt for the detector, one mask-decoder pass per proposed box, and two ways to be wrong that multiply instead of cancelling.

SAM 3 (Meta, November 2025) collapsed the cascade. Its task is Promptable Concept Segmentation: give it a short noun phrase — or an image exemplar — and it returns masks and unique instance IDs for every matching object in one forward pass. Not “segment this thing I pointed at” but “segment this concept”. The paper’s own framing is that the model has an image-level detector and a memory-based video tracker sharing a single backbone, with a presence head that decides whether the concept is even there.

2023SAMacceptspoint / boxViT encoder → prompt encoder → mask decoderno text anywhere in the modelone instance's mask2024Grounded SAM 2acceptstextGrounding DINO → boxes → SAM 2 → maskstwo models, frozen, errors accumulatemasks + masklets2025SAM 3acceptstext / exemplarshared backbone → detector + tracker + presenceone model, one forward passall matches + IDs
The prompt-mode ladder. Read it as a table of interfaces, not a ranking: each row still has a job in 2026. What changed is where the text lives — outside the model in 2024 (a detector’s input), and inside it in 2025 (a concept prompt).

Three differences matter when you write code against SAM 3. First, no per-instance prompting: one phrase returns all matches, so you stop looping over objects. Second, open vocabulary: the concept can be anything describable in a short noun phrase, not a fixed label set. Third, many instances at once: the output is a set of masks with distinct IDs, not one mask per call. The interface you build around those three facts is a different shape from a detector loop.

Keep the cascade’s trade-off in view, though, because it never disappears: SAM 3 is monolithic. You cannot swap its detector for a domain-specific one, you cannot tune the detector threshold the way you can when the detector is a separate package, and the released weights are gated on Hugging Face under a custom license. Grounded SAM 2 remains the modular option — and the lesson comes back to that when the choices get real.

Quick check

A colleague says: “SAM 3 can take a point click, so it is just SAM with text bolted on.” What is the most accurate correction?

THREE GENERATIONS OF PROMPTS

Click, then text-through-a-detector, then text.

The ladder is not a story about better models — it is three different interfaces with three different cost structures. Knowing which rung you are on explains the latency, the failure modes, and the code you are about to write.

Rung one: SAM (April 2023). A ViT encodes the image once — ViT-H is a 636M-parameter image encoder inside a 641.1M-parameter checkpoint whose fp32 weights are 2.56 GB, the file people quote as “2.4 GB” because 2.56 GB is 2.38 GiB. Then the prompt encoder and mask decoder answer each click in ~50 ms in a browser. A single click is ambiguous (the wheel of a bike, or the whole bike?), so SAM returns up to three masks with predicted IoU scores and lets a follow-up click disambiguate. The interface is a gesture, and the gesture cannot name anything.

Rung two: Grounded SAM 2 (2024). A text-conditioned detector turns a phrase into boxes, SAM 2 turns each box into a mask and — this is the 2024 addition — tracks it through video as a masklet, using a streaming memory that attends to previous frames. Promptable visual segmentation (PVS) lets you prompt on any frame and refine later. The cost structure is the cascade’s: one detector pass per prompt string, one image encode, and one mask decoder pass per box. Twelve instances of a concept are twelve decodes in rung two and a single concept pass in rung three.

Rung three: SAM 3 (November 2025). The phrase goes straight into the model. Promptable Concept Segmentation returns every matching instance with a mask and an instance ID, plus a presence score for the concept as a whole. The paper describes one shared backbone feeding an image-level detector and a memory-based video tracker, with a presence head decoupling “is it here?” from “where is it?”. Visual prompts still work; text and exemplars are added, not substituted.

STACKPROMPTCOST OF A QUERYTEXT LIVES…RETURNSSAM 11 point1 encode + 1 decodeper promptnone1 mask (+2 alt.)Grounded SAM 2text1 detector per prompt+ 1 decode per boxin the detectorN masks + IDsSAM 3text / exemplar1 vision encode+ 1 concept passin the modelall masks + IDs
The output contract barely changes; the cost model does. All three return boxes, scores and masks — SAM 3 adds unique instance IDs and a presence score — so your downstream code rarely has to branch on which rung produced the numbers. What changes is how many forward passes a query costs, and that is what the pipelining decisions hang on.

The prompt-mode comparator

One image, three ways to ask. Click a mode (or let the comparator cycle): a point returns one instance, text through a detector returns one mask per box, and text asked directly returns every match. Watch the pass counts change with the prompt — that is the whole lesson in one picture.

prompt mode
mode text introduced SAM 3 (Nov 2025) accepts one short noun phrase — "yellow school bus" returns masks + instance IDs for every match, plus a presence score, one forward pass per-instance prompting? no — one prompt, every match what that means Promptable Concept Segmentation: no per-instance pointing, no fixed label list, all instances at once. One concept per pass; batch or loop for more. forward passes, 3 concepts over this image SAM click 1 encode + 1 decode per click, cached after the first Grounded SAM 2 3 detector passes + 1 SAM 2 encode + 1 mask decode per box SAM 3 1 vision encode + 3 concept passes (all instances each) YOLO-World 3 detector passes, boxes only, no mask decoder source of the counts architectural pass counts, not timings — see the latency ladder lab

The three panels share one scene and one output contract (boxes, scores, masks, IDs). What changes is how the question is asked: a click is one instance, a cascade is text-plus-boxes, and a concept prompt is text with every match returned at once.

Watch the comparator cycle: the same five-object scene answers three different questions. A point returns one instance because a click can only mean “the thing I touched”. Text through a detector returns one mask per proposed box — the detector’s recall is the ceiling, and every box pays a decode. Text asked directly returns every match of the concept in one pass, and it can also answer nothing when the concept is absent, which the cascade cannot say cleanly.

Quick check

An annotator needs every one of 30 oranges in a packing-house photo, and the team cares about per-item masks. Which rung costs the fewest forward passes for that question?

ONE BACKBONE, FOUR JOBS

Detector and tracker share everything but their heads.

SAM 3 is one model doing two jobs that used to fight: recognise every instance of a concept (features that must be similar across instances) and keep each instance distinct over time (features that must be different). The published fix is a shared backbone with decoupled heads, plus a presence score that is allowed to say no.

The official paper describes SAM 3 as an image-level detector and a memory-based video tracker that share a single backbone. The blog adds the ancestry: the vision and text encoders come from Meta’s Perception Encoder, the detector is DETR-based, and the tracker builds on SAM 2’s memory bank and memory encoder. Four jobs sit on that one encode:

  • Recognise — the text (or exemplar) encoder turns the concept into a query, and the detector scores image regions against it.
  • Localise — the same detector regresses the boxes and instance queries that the mask decoder turns into masks.
  • Decide presence — a separate scalar head answers “does this concept exist in this image?” before anything is localised. Meta’s own summary says recognition and localisation are decoupled with a presence head, which boosts detection accuracy.
  • Track — on video, per-instance memory carries identity across frames, and an occlusion head marks frames where the instance is not visible instead of deleting it.

The decoupling is not cosmetic. Re-detecting an instance every frame wants features that are invariant across viewpoints; keeping two similar instances apart wants features that are discriminative. Those pull in opposite directions, which is why the detector and the tracker are separate heads over shared features rather than one head doing both. The same instinct is why the presence head exists: a detector forced to answer every query will rank something highest even when the concept is absent, and a scalar veto fixes that cleanly.

image 1008²text promptbox / pointSHARED BACKBONEvision encoder32-layer ViT · 5184 tokFPN · 256 ch288² / 144² / 72² mapstext encodergeometry encoder3 layers · RoI 7one encode, all jobsIMAGE DETECTOR (DETR)encoder 6 · decoder 6 layers200 object queries→ boxes + instance queries"where are the matches?"PRESENCE HEAD"is the concept here at all?"MASK DECODER3 upsampling stagesmasks + instance IDsMEMORY-BASED VIDEO TRACKER (SAM 2 lineage)per-frame features shared by every object · memory encoder + memory bank6 recent frames + prompted frames · occlusion head says "not visible"decoupled from the detector so re-detection and tracking do not fight
The forward pass, with the published component sizes from the transformers configuration: a 32-layer ViT at 1008 px (patch 14 → 72 × 72 = 5,184 tokens), an FPN with 256 channels producing 288², 144² and 72² maps, a 3-layer geometry encoder for visual prompts, a DETR encoder and decoder of 6 layers each with 200 object queries, and a mask decoder with 3 upsampling stages. The tracker half is the SAM 2 lineage: memory encoder, memory bank, occlusion head.
The stage arithmetic, counted honestly
one image, one concept prompt: encode 1 vision pass (32-layer ViT over 5,184 tokens) text 1 text encode detect 1 detector pass (6 + 6 DETR layers, 200 queries) presence 1 scalar for the whole concept (the presence head) decode 1 mask pass (3 upsampling stages) = 5 stages of work, one forward pass in the API sense the same image, N concepts: 1 vision encode + N text/detect/decode passes the same image through Grounded SAM 2, N concepts and B boxes: N detector passes + 1 SAM 2 encode + B mask decodes → the cascade's cost grows with instances, not just concepts a video frame, C concepts and O objects: 1 vision encode per frame + C detector passes per frame + tracker passes per frame: O before Object Multiplex, ceil(O / 16) since SAM 3.1 what is measured, not derived: SAM 3 image 30 ms, 100+ objects, H200 SAM 3.1 video 16 → 32 FPS, up to 16 objects per pass, H100 SAM 2.1 frame times 11.0 / 11.8 / 15.6 / 25.3 ms at 1024 px, A100 SAM 1 click path ~50 ms for the prompt encoder + mask decoder the transformers API used in chapter 05: image Sam3Processor / Sam3Model, post_process_instance_segmentation video Sam3VideoModel / Sam3VideoProcessor, init_video_session, add_text_prompt, propagate_in_video_iterator, postprocess_outputs cache get_vision_features once, get_text_features once — then reuse
OCCLUSION IS NOT ABSENCE

Detection answers a frame.
Memory answers the clip.

A bus passes behind a building for three frames. A detector that runs per frame sees it vanish and calls the next appearance a new object. SAM 2’s memory bank is the mechanism that keeps the identity — and SAM 3 inherits it, then makes many-instance tracking affordable.

SAM 2 (2024) generalised promptable segmentation to video with a streaming architecture: frames are consumed one at a time, and the mask decoder’s input is not the raw image embedding but an embedding conditioned on memories of past frames. The memory encoder downsamples the predicted mask, fuses it with the frame’s image embedding, and stores the result in a memory bank: a FIFO queue of up to six recent frames plus a second queue of prompted frames. Cross-attention reads that bank, and a per-object object pointer (a 256-dimensional vector split into four 64-dimensional tokens) carries the high-level “which object is this” signal.

The second new piece is the occlusion head — SAM 2’s answer to frames where the object is genuinely not visible. SAM always assumed there was a valid object given a positive prompt; in video that is false, and a tracker that has to emit a mask on every frame will hallucinate one behind the building. The occlusion head adds a learned embedding to the memory features of hidden frames and produces a visibility score, so the model can say “not visible” while keeping the object alive in memory. That is the difference the stepper lab is built to show.

frame 0id 7frame 1id 7frame 2id 7frame 3occludedframe 4occludedframe 5occludedframe 6id 7frame 7id 7frame 8id 7MEMORY BANK · FIFO OF 6 RECENT FRAMES + PROMPTED FRAMES · PER OBJECTthe queue is what carries id 7 across frames 3-5no mask is emitted while hidden — the tracker is not guessing pixels, it is preserving identity
Nine frames, one occlusion, one identity. The queue is never a subscription to immortality — objects that leave the scene for good do eventually get dropped by the association heuristics — but a three-frame occlusion is exactly the case memory exists for.

The memory tracker stepper

Step through the twelve frames. Frames 4-6 put the bus behind a building corner: the presence head reports it as not visible, no mask is emitted, and the memory bank is what carries the identity across the gap. Flip memory off and the same three frames cost you the ID.

frame 0 / 11 caption prompt frame — the masklet starts here presence 0.98 (visible) instance id 7 memory 1 recent slots + prompt t0 the published dimensions behind the bank (SAM 2 paper) recent frames kept 6 prompted frames a second FIFO, kept when provided memory feature 64 channels at 1/16 resolution = 64 × 64 per frame at 1024 px object pointer 256-dim, split into 4 × 64 tokens memory attention 4 transformer layers arithmetic (derived) one memory frame 64 × 64 × 64 × 4 B = 1.0 MB one object's bank 7.3 MB for 7 slots twelve objects 88.1 MB if every object keeps its own bank SAM 3.1 (Mar 2026) Object Multiplex tracks up to 16 objects in one forward pass and doubles throughput 16 → 32 FPS on an H100 for medium object counts: the per-object banks become one shared memory with per-instance queries.

An occlusion head is not a nicety: without it, every hidden frame looks like the object vanished, and a tracker that deletes vanished objects has to re-identify them when they come back. Memory plus an explicit “not visible” verdict is what turns detection into tracking.

SAM 3 keeps the architecture and changes the economics. The tracker is still memory-based, reading the same shared per-frame features; what used to be expensive was that every object ran its own memory bank and decoder, so cost grew linearly with the number of instances. The March 2026 SAM 3.1 update, Object Multiplex, replaces the per-instance banks with one shared memory plus per-instance queries: up to 16 objects in a single forward pass, and for a medium number of objects, throughput on one H100 doubles from 16 to 32 FPS. For crowds and dense scenes that is the difference between tractable and not — and it is where this lesson hands off to Lesson 27: the classical trackers (SORT and ByteTrack) solve the same problem by detecting every frame and associating boxes, and this memory-based family is what took over when identity, not boxes, became the product.

One honesty note before you deploy it: the transformers video configuration documents a hotstart window of 15 frames that removes unmatched and duplicate tracks using future frames — and streaming inference, by definition, has no future. The docs say streaming “may result in more false positive detections and duplicate object tracks”, so use pre-loaded inference when the clip is available and accept the trade-off only when it is not.

Quick check

The presence head reports 0.08 for three consecutive frames while the tracker keeps the object's ID. What is the most likely situation?

PROMPTS IN, MASKS OUT

The model boundary is a short noun phrase.

Everything between a user’s sentence and a runnable prompt is code you write: split concepts, cache the encode, return one detection contract. This chapter is the interface layer the source builds — plus the actual Hugging Face calls that sit behind it.

The first job is turning “what the user typed” into “what the model consumes”. SAM 3 takes one concept per forward pass, so a sentence with conjunctions has to be split into short noun phrases — heuristic, imperfect, and worth doing explicitly instead of letting a model guess. The source’s splitter normalises the common separators and returns a list.

split_concepts — the user/model boundarypython
def split_concepts(sentence):
    """Heuristic splitter for multi-concept prompts."""
    normalised = sentence
    for sep in [" and ", " or ", "&", ";"]:
        normalised = normalised.replace(sep, ",")
    if "," in normalised:
        parts = [p.strip() for p in normalised.split(",")]
        return [p for p in parts if p]
    return [sentence.strip()]

print(split_concepts("cats, dogs and balloons"))
# ['cats', 'dogs', 'balloons']
print(split_concepts("candy-striped red umbrella"))
# ['candy-striped red umbrella']   <- hyphens are not separators
One prompt per concept per forward pass. The splitter is a heuristic: 'candy-striped' survives because only the listed separators split, while 'and' always does.

The second job is the output contract. SAM 3, Grounded SAM 2 and YOLO-World all return boxes, labels and scores; the segmentation models add masks, and SAM 3 adds unique instance IDs. Your pipeline should not care which backend ran, so the source defines one dataclass and encodes masks as run-length runs — the same format SAM 2, SAM 3 and COCO use, and the reason a mask can travel through JSON at all.

ConceptDetection + RLE — one contract for every backendpython
from dataclasses import dataclass

@dataclass
class ConceptDetection:
    concept: str
    instance_id: int
    box: tuple          # (x1, y1, x2, y2)
    score: float
    mask_rle: str       # run-length encoded, e.g. "0x100;1x50;0x200"

def rle_encode(binary_mask):
    flat = binary_mask.flatten().astype("uint8")
    runs, prev, count = [], int(flat[0]), 0
    for v in flat:
        if v == prev:
            count += 1
        else:
            runs.append((prev, count)); prev, count = v, 1
    runs.append((prev, count))
    return ";".join(f"{value}x{length}" for value, length in runs)
A 640×480 bus mask in this lab is 307,200 raw bytes; this format needs 961 runs and 5,765 characters, about 53× smaller — because a mask is one blob, not noise.

That 53× is the whole reason RLE is on the wire, and it comes with a warning worth internalising: the win is a property of the image, not of the format. Encode a checkerboard and every pixel alternates, so runs are one pixel long and each one costs about four characters — the “compressed” payload is four times the raw bitmap. Mask formats that also accept polygons and PNG exist for exactly this reason: pick the encoding that matches your shapes.

Behind the contract sits a real model call. Hugging Face’s transformers integration exposes Sam3Processor and Sam3Model for images, and — this is the part that makes the pass-count arithmetic real — get_vision_features and get_text_features so the vision encode is paid once per image and reused across concepts.

SAM 3 in transformers — text prompt, cached encode, one call per conceptpython
import torch
from transformers import Sam3Processor, Sam3Model
from PIL import Image

model = Sam3Model.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3Processor.from_pretrained("facebook/sam3")

image = Image.open("shelf.jpg").convert("RGB")

# 1) pay the vision encoder once per image ...
img_inputs = processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
    vision_embeds = model.get_vision_features(pixel_values=img_inputs.pixel_values)

# 2) ... and ask as many concept prompts as you like against the cache
for concept in ["yellow school bus", "striped red umbrella", "banana"]:
    text_inputs = processor(text=concept, return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model(vision_embeds=vision_embeds, **text_inputs)
    results = processor.post_process_instance_segmentation(
        outputs,
        threshold=0.5,          # score threshold
        mask_threshold=0.5,     # mask binarisation
        target_sizes=img_inputs.get("original_sizes").tolist(),
    )[0]
    print(concept, len(results["masks"]), "instances")

# results: masks (binary, original size), boxes (xyxy pixels), scores
transformers v5.17.0 API. The same processor also takes input_boxes / input_boxes_labels for visual prompts (1 = positive, 0 = negative, -10 = padding), and the model returns outputs.semantic_seg alongside instance masks.

Video uses the detector and tracker as one object: Sam3VideoModel wraps a detector (SAM 3) and a SAM 2-style tracker, and you drive it through an inference session. Text prompts are added once; the tracker then propagates the masklets frame by frame, and each frame’s output maps a prompt to its object IDs. Multiple prompts are processed in a single pass with shared vision features, which is the multiplexing idea already visible at the API level.

SAM 3 video — an inference session, not a loop you writepython
from transformers import Sam3VideoModel, Sam3VideoProcessor
from transformers.video_utils import load_video

model = Sam3VideoModel.from_pretrained("facebook/sam3", device_map="auto")
processor = Sam3VideoProcessor.from_pretrained("facebook/sam3")

frames, _ = load_video("clip.mp4")
session = processor.init_video_session(
    video=frames, inference_device=device,
    processing_device="cpu", video_storage_device="cpu",
)
session = processor.add_text_prompt(session, ["person", "bed", "lamp"])

for frame_output in model.propagate_in_video_iterator(session):
    out = processor.postprocess_outputs(session, frame_output)
    # out["object_ids"], out["scores"], out["boxes"], out["masks"],
    # out["prompt_to_obj_ids"] -> {"person": [0, 3], "bed": [1], ...}
Pre-loaded video uses hotstart heuristics (15-frame window) that remove unmatched and duplicate tracks; the streaming path cannot, and the docs warn it may produce more duplicates. Use streaming only when frames truly arrive live.

The concept segmentation simulator

Choose a concept prompt. The model answers two questions in one pass — is it here (presence), and where is every instance (masks + IDs). Switch the presence head off and ask for something absent: the detector still answers, which is the failure mode the head exists to prevent.

concept prompt
concept "yellow school bus" presence 0.96 (present, threshold 0.50) verdict presence 0.96 ≥ 0.50 → 2 instances above 0.50 returned id bus-a score 0.94 id bus-b score 0.81 vetoed by the presence head none why this concept is interesting Common, visually distinctive, two instances: the easy case for every model in the lesson. payload arithmetic (derived, this lab) raw mask 640 × 480 = 307,200 bytes RLE 961 runs → 5,765 characters shrink 53.3× — because the mask is one blob, not noise passes for this run 1 vision encode + 1 concept pass (presence + detector + mask decoder)

The presence score is a scalar, separate from the masks. That is what makes “there is no banana here” a real answer instead of a confession buried in low confidence scores.

The last piece of the interface is a fallback. When the real model is not loaded — in unit tests, in CI, on the machine of the person reviewing your PR — you still want the pipeline to run. The source wraps every backend behind one abstract class and ships a StubOpenVocabSeg that returns deterministic detections for a given image size. Your downstream code never learns whether it is talking to SAM 3, Grounded SAM 2, or a stub; that is the point.

Quick check

You have 20 concept prompts to run on one image with transformers. What is the correct shape of the calls?

WHICH MODEL, WHEN

The right tool is the lightest one that answers your question.

Three axes decide almost every open-vocabulary deployment: does the task need masks and tracking, how strange are the concepts, and what can the target hardware afford? Everything else is taste.

Axis one: the output. Boxes-only at high frame rate is a different problem from masks. YOLO-World is the detection-only tool — the paper reports 35.4 AP zero-shot on LVIS at 52.0 FPS on a V100 at 640², which is 19.2 ms per frame — and it has no mask decoder to pay for. If your dashboard counts objects and draws rectangles, adding masks is pure cost. If a downstream step needs silhouettes — area, shape, touching-instance separation — you need a segmentation model and the comparison starts at rung three.

Axis two: concept complexity. Common single-word concepts are solved roughly equally by everything; the differences appear on rare and compositional phrases — “striped red umbrella”, “person holding a mug” — and on concepts that are absent from the image, where the presence head is the structural advantage. But the axis has a far end: Meta documents SAM 3 as weak on fine-grained out-of-domain concepts even zero-shot, naming terms that need domain knowledge such as “platelet” in medical imagery. When your concepts are like that, no stack choice saves you; the answer is fine-tuning on in-domain annotations, and the release ships fine-tuning code for exactly this reason.

Axis three: the deployment. SAM 3 is monolithic — one model, one license, one threshold behaviour. Grounded SAM 2 is a composition you can rewire: swap in DINO-X, Florence-2, or Grounding DINO 1.5; tune the detector threshold yourself; keep research ablations valid while you hold SAM fixed. Add the practical constraints — the released SAM 3 weights are gated on Hugging Face under a custom license, and the model is ≈860M parameters / 3.44 GB in fp32 — and modularity stops looking like nostalgia.

need masks?the first forknoYOLO-WORLDboxes only · 35.4 AP LVIS zero-shot52.0 FPS at 640² on a V100 (19.2 ms)yesswap detector / license?modularity is a requirementGROUNDED SAM 2detector + SAM 2, frozen, swappableN detector passes + 1 decode per boxno: SAM 3 (text in one pass) · SAM 3.1 for videorare / fine-grained concepts: fine-tune on in-domain data before trusting any branch
The production split from the source, drawn as a fork: YOLO-World for fast detection-only pipelines (robotics navigation, fast dashboards), SAM 3 for anything that needs masks or tracking, Grounded SAM 2 when modularity is the requirement. SAM-MI addresses the decoder bottleneck with sparse point prompting, shallow mask aggregation and decoupled mask injection — the source reports 96% fewer decoder calls and about 1.6× over Grounded-SAM on open-vocabulary benchmarks.

The open-vocabulary stack chooser

Four axes decide almost every open-vocabulary deployment: does it need masks, does it need tracking, how many concepts and objects, and what latency and license constraints apply. Pick a use case and read the recommendation, the pipeline, and the one thing that breaks it.

An annotator clicks each object in a still image. Latency per click decides whether the tool feels instant.
RecommendationSAM 3 visual prompts, or classic SAM if you only need points and boxes
Pipelineimage → vision encode once → per click: prompt encoder + mask decoder
Deciding metricms per click (SAM paper: ~50 ms with the embedding cached) — not ms per image
GotchaThe encoder is the expensive part and it must not run per click. Cache the image embedding; a click that rebuilds it misses the interactive budget.
Output formatmasks (N, H, W) + per-prompt scores; instance IDs only once a concept prompt is used
USE CASE · Interactive labelling — one click per object tags · visual prompts · images · latency < 100 ms the four questions, applied 1 masks? yes — pixel-accurate output required 2 tracking? no — single image or single frame 3 concepts one to a few, per prompt 4 budget ms per click (SAM paper: ~50 ms with the embedding cached) — not ms per image the dated-snapshot rule every model number in this lesson was checked on 2026-09-16 and names its version and hardware: SAM 3 (Nov 2025), SAM 3.1 (Mar 2026), SAM 2.1 (2024), YOLO-World (Jan 2024). Re-check before you ship.
WHAT EACH TOOL RETURNS SAM (2023, visual prompts) masks + per-prompt scores. No text, one instance at a time. Grounded SAM 2 (2024, cascade) detector boxes + SAM 2 masks + masklet tracking. Two models, two error sources, detector swappable. SAM 3 (Nov 2025, PCS) masks + instance IDs + presence for every match of a text or exemplar prompt. Video via a memory-based tracker. SAM 3.1 (Mar 2026) the same, with Object Multiplex: up to 16 objects per forward pass, 16 → 32 FPS on an H100 for medium object counts. YOLO-World (Jan 2024) open-vocabulary boxes only, real time: 35.4 AP zero-shot on LVIS at 52.0 FPS on a V100 at 640². SAM-MI (2025-2026, from the source) efficiency work on the decoder bottleneck: the source reports 96% fewer decoder calls and ≈1.6× over Grounded-SAM. PICK BY OUTPUT, THEN BY WEIGHT boxes only → YOLO-World masks, one instance, clicks → SAM / SAM 2 masks by text, images → SAM 3 masks by text, video → SAM 3 (or SAM 2.1 with human prompts) detector swap / licenses → Grounded SAM 2

The honest default for 2026 open-vocabulary segmentation is SAM 3; the honest exception is any deployment where you need to choose the detector, the license, or the threshold yourself — that is what Grounded SAM 2 is for.

The latency ladder

Pick a stack and a budget. The board shows the stages it runs, the passes each stage costs, and the measured number where one exists — with the arithmetic visible. Grounded SAM 2 has no single published end-to-end time here, so the lab shows pass counts instead of inventing a total.

SAM 3 · one image · budget: video · 30 fps · 33.3 ms
StagePassesBasis
vision encode1cacheable with get_vision_features
concept pass (detector + presence + mask)3one short noun phrase per pass; all instances returned together
Total passes (this workload)43 concepts, 6 boxes, 4 tracked objects
Measured / derived time30.0 ms (30 ms)

Fits video · 30 fps · 33.3 ms: 3.3 ms of headroom per one frame every 33.3 ms.

THE LADDER, TOP TO BOTTOM prompt a click, a box, a noun phrase, an exemplar encode the per-image / per-frame vision pass — cache it SAM 3: 32-layer ViT at 1008 px, 72 × 72 = 5,184 patches decode detect + localise: DETR 6 + 6 layers, 200 queries, mask decoder with 3 upsampling stages (transformers config) track per-frame memory + mask decoder per object; multiplexed since SAM 3.1 PUBLISHED NUMBERS THIS LAB USES SAM click path ~50 ms SAM paper: prompt encoder + mask decoder answer in ~50 ms in a web browser, image embedding already computed SAM 3 image 30 ms single image, 100+ detected objects on an H200 SAM 3.1 video 32 FPS up to 16 objects per pass on an H100 SAM 3 video claim near real-time for ~5 concurrent objects YOLO-World 52.0 FPS → 19.2 ms 35.4 AP zero-shot on LVIS at 640² on a V100 SAM 2.1 FRAME TIMES (full pipeline, A100, 1024 px) sam2.1_hiera_tiny 38.9M 91.2 FPS 11.0 ms SA-V 76.5 sam2.1_hiera_small 46M 84.8 FPS 11.8 ms SA-V 76.6 sam2.1_hiera_base_plus 80.8M 64.1 FPS 15.6 ms SA-V 78.2 sam2.1_hiera_large 224.4M 39.5 FPS 25.3 ms SA-V 79.5 at 30 fps (33.3 ms) every size fits; at 60 fps (16.7 ms) only tiny and small do WHAT IS NOT MEASURED HERE the cascade's end-to-end cost — it depends on the detector checkpoint; the per-concept cost of extra concepts on the same image for SAM 3; your own resolution, batch size and precision. Measure those.
stack
budget
selected SAM 3 · one image measured 30 ms basis single image with 100+ detected objects on an H200 (Meta, Nov 2025) verdict fits the 33.3 ms budget with 3.3 ms to spare passes 4 across 2 stages vision encode 1× concept pass (detector + presence + mask) 3× the count that matters most concept passes after one cached vision encode

Interactive budgets and streaming budgets are different problems: SAM’s ~50 ms buys 10 clicks a second on one cached image, while video asks for a whole frame in 33.3 ms at 30 fps — and that is why the SAM 2.1 tiny checkpoint and multiplexed tracking exist.

When you migrate from Grounded SAM 2 to SAM 3, the source’s advice is to audit three things instead of assuming a clean upgrade. Latency is usually net-neutral or a slight win — you delete a detector pass, but the surviving model is heavier — so measure the end-to-end pipeline, not the model card. Accuracy shifts by concept: rare and compositional phrases gain the most, common single-word concepts look similar, and your own long tail is the only sample that matters. Flexibility is a real loss: you can no longer choose the detector, so if a domain-specific detector was carrying your accuracy, do that comparison before you swap. The source packages both decisions as two artifacts — a stack-picker prompt and a concept-prompt designer skill that turns user utterances into well-formed prompts with disambiguation and fallbacks — and this lesson’s chooser and splitter are the same two shapes.

When you do not want to write the session plumbing yourself, Ultralytics wraps the weights behind the interface it already uses for YOLO and SAM 2 — same call shape, different model name. That is a perfectly good production choice for straightforward image work; the lesson spells out the transformers path because it is the one you extend.

The same interface, one model string awaypython
from ultralytics import SAM

model = SAM("sam3.pt")
results = model(image_path, prompts="yellow school bus")
# results[0].boxes, results[0].masks — the usual Ultralytics objects
The source's example. Wrappers reduce integration work; they do not change the underlying pass counts, so the budget arithmetic still applies.
READING THE CLAIMS HONESTLY

“Open vocabulary” is a direction, not a warranty.

Every model in this lesson is described with a number that was true on a benchmark, on a GPU, on a date. This chapter is the discipline that keeps those numbers from turning into a bug report: label the snapshot, separate the claims, and audit per-concept.

Start with what open vocabulary can and cannot mean. A concept prompt can be any short noun phrase, but the model’s ability to ground it comes from training data. Meta’s own limitations section says SAM 3 struggles to generalise to fine-grained out-of-domain concepts zero-shot — the example given is “platelet” in medical imagery — and that it does not support longer, complex phrases like “the second to last book from the right on the top shelf”. That second limitation is architectural: PCS takes short phrases, so reasoning-heavy queries are handled by a multimodal model that proposes noun phrases and inspects the masks, iterating until satisfied. Meta calls that pattern SAM 3 Agent, and it is a useful mental model for your own product: the language model does the reasoning, the segmentation model does the pixels.

The second honesty problem is per-concept ambiguity. “A player in white” and “a player in red” are two concepts and two sets of instances; evaluating them together as “player” hides exactly the errors that matter. This is why the presence head helps — it sharpens closely related prompts — and why SA-Co contains hard negatives (concepts deliberately not present) alongside positives. If your evaluation averages over a whole vocabulary, the number will look fine while the concepts you care about are broken. Audit per concept, and include absent concepts: a false positive on “hard hat” in a safety system is not noise, it is a wrong alert.

The third is simply dating. “SAM 3”, “SAM 3.1” and “SAM 2.1” are different checkpoints with different numbers; the mask-decoder timings in the 2023 paper were taken in a browser; the frame rates in the SAM 2 release were measured on an A100 at 1024 px; the SAM 3 figures come from an H200 and an H100. A production decision that quotes any of them without the hardware and version is a decision with a hidden variable. This page checked its numbers on 2026-09-16 and says so everywhere it repeats them.

The claims ledger — every 2025-2026 number in this lesson, who says it, and the sentence it does not license.
ClaimSource & dateWhat it does not mean
2× cgF1 over existing systems on SA-Co, image and videoMeta, SAM 3 announcement (Nov 2025)a dated benchmark result on a specific benchmark, against specific baselines — not a promise for your concepts
SAM 3 reaches 74% of estimated human performance on SA-Co/Gold (image) and over 80% of human pHOTA on SA-Co/VEval (video)SAM 3 paper (arXiv 2511.16719)a benchmark study, with the metric named; read the paper's tables before quoting it in a product decision
SA-Co holds 207K unique concepts, over 50× prior open-vocab benchmarksSAM 3 paper (arXiv 2511.16719)coverage, not accuracy: a bigger vocabulary still has holes, and your domain may be one
30 ms per image with 100+ objects; 16 → 32 FPS on an H100Meta (Nov 2025; SAM 3.1, Mar 2026)measured on an H200 / H100 with specific settings — your resolution, concepts and objects move these numbers
~5× faster than humans on negative prompts, 36% on positive onesMeta's data-engine reportan annotation-speed result, not an inference-latency one — the two get confused constantly
SAM-MI: 96% fewer decoder calls, ≈1.6× over Grounded-SAMthe vendored lesson sourcean efficiency paper's headline; useful direction, still someone else's benchmark
Read the third column as the interesting one. A benchmark number is a measurement under stated conditions; the sentence that turns it into an engineering claim — “so it will do this for us” — is always an inference. State the conditions, then make the inference explicitly.

Finally, the boring constraint that ends more projects than accuracy: licensing and access. The facebook/sam3 checkpoint on Hugging Face is gated (manual approval) under a custom license — verified on this page’s check date — while SAM 2’s checkpoints and training code are Apache 2.0 and YOLO-World’s repo is public. If your legal team needs a permissive licence, Grounded SAM 2 is the rung that ships today; if it needs the best open-vocabulary masks and can accept the terms, SAM 3 is the default. Neither answer is a formula — it is a decision with a date on it.

CHECK YOURSELF

Six questions.
Then the terms worth keeping.

Answer before you look. The presence-head question and the “what does the 50 ms include” question are the two that separate “I read about SAM 3” from “I could budget a deployment this week.”

0 / 6 answered · 0 correct

01What is Promptable Concept Segmentation (PCS), introduced by SAM 3?

02Why keep a decoupled detector + SAM 2 pipeline (Grounded SAM 2) in 2026 if SAM 3 already does text-prompted segmentation?

03SAM 3's presence head produces what?

04SAM 3.1 Object Multiplex (March 2026) introduced a shared-memory mechanism for tracking. What does it replace?

05You need real-time open-vocabulary DETECTION (boxes only, no masks) on an edge device. Which model family fits?

06The SAM paper reports that the prompt encoder and mask decoder answer a prompt in ~50 ms in a web browser. What does that 50 ms include, and what does it exclude?

Key terms, demystified

Click a card to swap the lazy description for what it actually means — each one carries the number, the version and the date from the lesson.

Exercises from the lesson

Four problems with real arithmetic: a 10-image, three-concept comparison with per-concept honesty; a click-to-include/exclude loop and what it cannot fix; a fine-tune budget for 100 images of electronic components; and a pass-and-memory audit that decides whether a 12 fps, four-object stream needs Object Multiplex. Try first; a worked answer is one click away.

  1. Easy — Run one image-level model on 10 images with three concept prompts each (one common single-word, one compositional, one absent), and compare against SAM 2 + Grounding DINO 1.5 on the same images. For each concept report: how many instances were returned, whether the absent concept returned zero detections, and what the presence score was. Then count forward passes per concept for both stacks.
    Show one worked answer

    The comparison is only meaningful if you hold the prompt fixed: same 10 images, same three strings, same score threshold. Expect the common concept ("bus") to look similar across both; the compositional one ("striped red umbrella") to favour SAM 3, which is the case the source calls out; and the absent concept to expose the presence head, where SAM 3 can return zero detections at a low presence score while the cascade must rely on the detector's threshold, and often returns something. Count the passes honestly: SAM 3 image is one vision encode (amortised across the three prompts if you cache embeddings) plus one concept pass each — 1 + 3; Grounded SAM 2 is one detector pass per prompt plus one SAM 2 mask-decoder pass per proposed box, so 3 prompts and, say, 11 boxes is 3 + 1 + 11 = 15 model stages, with two sets of weights resident. Report the counts next to the quality delta, because the lesson's point is that the winner depends on which axis you are measuring.

  2. Medium — Build a click-to-include / click-to-exclude UI on top of SAM 3: a text prompt returns candidate instances; the user clicks keep/drop on each. Output the final concept set as JSON. Say what changes in the model call when the user excludes an instance, and what you cannot fix with this loop.
    Show one worked answer

    The straightforward version runs the text prompt once, renders every candidate mask with its instance_id and score, and records keeps/drops in a set — the JSON is concept, kept instance_ids, per-instance box, score and mask RLE. The interesting part is the exclusion mechanic. If your backend exposes visual prompts, a negative box (input_boxes_labels 0, positive 1, padding -10 in the transformers convention) on the dropped instance re-runs the detector and suppresses that region, which is a real model call, not a filter. If it does not, you are post-filtering: free, deterministic, and it fixes nothing about missed instances. Neither loop can recover an instance the model never proposed — a false negative needs a reworded prompt or an exemplar, and that is the coverage limit of the approach.

  3. Hard — Fine-tune SAM 3 on five types of electronic components, 20 labelled images each. Compare zero-shot and fine-tuned mask IoU on a held-out set of 50 images. Give the parameter and memory budget for the run, and the one place the published 30 ms / 100+ objects number stops applying.
    Show one worked answer

    The facebook/sam3 checkpoint is 859,922,360 parameters — 3.44 GB fp32, half that in bf16 — and the fine-tuning code is released with the weights. At 100 images total you are firmly in adapt-don't-retrain territory: freeze the vision encoder and train the detector and mask-side modules, or use the released fine-tuning recipe with a small learning rate; 100 images do not justify updating a 32-layer, 1024-wide ViT. Budget the fixed cost honestly: 3.44 GB of weights, plus gradients and optimizer state for whichever subset you unfreeze, plus activations at 1008 px (the 5,184-token grid is what makes the encoder pass expensive). Report zero-shot vs fine-tuned mask IoU per concept and the confusion between visually similar parts, because fine-grained out-of-domain concepts are exactly where Meta documents SAM 3 as weak zero-shot. The 30 ms / 100 + objects figure was measured on an H200 for one image at default resolution with a single concept — it does not transfer to your batch size, your 560-px downscale (which the docs warn degrades accuracy), or five concepts per image.

  4. Numeric audit — A 12 fps stream, three concepts per image, about four tracked objects per concept, one H100. Count the model passes per frame and the memory the tracker keeps for each object, then decide between per-instance banks and Object Multiplex. State which numbers are published and which are arithmetic on published dimensions.
    Show one worked answer

    Published: memory features are 64 channels at 1/16 resolution and the memory bank keeps up to six recent frames plus prompted frames (SAM 2 paper); Object Multiplex holds up to 16 objects in one pass and doubles throughput from 16 to 32 FPS on an H100 (March 2026 announcement). Arithmetic: at 1024 px the 1/16 map is 64 × 64, so one memory frame is 64 × 64 × 64 × 4 B = 1,048,576 B ≈ 1.05 MB; a bank with six recent plus one prompted slot is ≈7.3 MB per object; 12 objects (three concepts × four instances) would be ≈88 MB of separate banks, versus one shared memory plus per-instance queries under Multiplex. Passes per frame: SAM 3's detector runs per concept, and the tracker was one pass per object before 3.1 — so 3 concept passes + 12 tracker passes ≈ 15 against 3 + 1 = 4 with multiplexing (the source's own description: 16 objects in a single forward pass). 12 fps needs 83 ms per frame; the published 32 FPS is 31.25 ms for a medium object count, so there is headroom, but verify on your concepts — the published figure is a benchmark, not a promise for your scene.

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • Open-vocabulary classification (CLIP)Lesson 18 gave you the trick behind every text prompt here: put text and images in one embedding space and score them against each other, so the label set is open. SAM 3 adds localisation and instance separation on top — it has to answer "where, which one", not just "is this a bus?" — but the reason "striped red umbrella" can work at all is the contrastive text-image training CLIP established. Phase 4, Lesson 18.
  • Instance masks and the detection contractSAM 3's output is Lesson 08's contract with IDs: boxes, labels, scores, per-instance masks. The difference is how the boxes are produced — a text-grounded detector inside the same model instead of an RPN, and "every matching instance" instead of "every proposed region". The RLE payload and the (N, 1, H, W) mask tensor downstream are the same. Phase 4, Lesson 08.
  • Segmentation masks and IoUPromptable segmentation is still segmentation: masks, mask IoU, and the same failure modes at boundaries. The new axis is that the *prompt* decides what counts as an object, which is why the lesson spends a chapter on evaluation honesty — a mask can be pixel-perfect for a concept the user did not mean. Phase 4, Lesson 07.
  • Boxes, NMS and real-time detectionYOLO-World exists because Lesson 06's detector line kept improving: anchors and NMS became RepVL-PAN and region-text contrastive loss, and boxes stayed boxes. When your pipeline only needs boxes, you skip the mask decoder entirely and inherit the detector's frame rate. Phase 4, Lesson 06.
  • Video as a sequence of framesSAM 2 and SAM 3 treat a video as frames consumed one at a time, exactly like Lesson 12's video models, and add one new object: memory. The tracker carries per-instance features across frames so a masklet survives motion, deformation and occlusion, and an occlusion head distinguishes "temporarily hidden" from "gone". Phase 4, Lesson 12.
  • Vision transformers and patch tokensSAM 3's image encoder is a 32-layer ViT at 1008 px: patch size 14 gives a 72 × 72 = 5,184-token grid, and the detector reads FPN maps at 288², 144² and 72² built from it. Every backbone the lesson compares — ViT-H in SAM, Hiera in SAM 2, the Meta Perception Encoder in SAM 3 — is a choice about how expensive that one per-image forward pass is. Phase 4, Lesson 14.
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Original lessonSAM 3 & Open-Vocabulary SegmentationAI Engineering from Scratch · the source text, quiz and main.py this lesson adapts: split_concepts, the ConceptDetection dataclass, RLE encode/decode, the OpenVocabSeg interface and StubOpenVocabSeg, the transformers Sam3Processor/Sam3Model snippet and the Ultralytics SAM("sam3.pt") wrapper.Founding paperSegment AnythingKirillov et al., April 2023 · the visual-prompt-only model this lesson's ladder starts from: points, boxes and masks, the ~50 ms prompt-encoder + mask-decoder path in a browser, three ViT sizes, and SA-1B's 11M images / 1.1B masks. The released model does not take text; the paper only shows initial text-prompt results.Video memorySAM 2: Segment Anything in Images and VideosRavi et al., 2024 · promptable visual segmentation, the streaming memory bank (up to 6 recent frames plus prompted frames, 64-channel memory features, 256-dim object pointers split into 4 × 64 tokens), the occlusion/presence head, and the Hiera checkpoints at 38.9M / 46M / 80.8M / 224.4M with the A100 frame rates this lesson's latency ladder uses.SAM 3SAM 3: Segment Anything with ConceptsMeta, November 2025 (arXiv 2511.16719) · Promptable Concept Segmentation, one shared backbone with an image detector plus a memory-based tracker and a presence head, the 4M-concept data engine and SA-Co. Checked 2026-09-16: the November 2025 announcement reports 2× cgF1 over prior systems, 30 ms per image with 100+ objects on an H200, and the March 27, 2026 SAM 3.1 Object Multiplex update (16 objects per pass, 16 → 32 FPS on H100). The facebook/sam3 checkpoint is gated on Hugging Face with a custom license: 859,922,360 parameters, 3.44 GB.SAM 3.1 releaseSegment Anything Model 3 — Object MultiplexMeta's official announcement (March 27, 2026) · the primary source for the SAM 3.1 update quoted in the version-pinning and latency chapters: one shared memory with per-instance queries instead of one memory bank per tracked object, up to 16 objects in a single forward pass, and 16 → 32 FPS on one H100 for a medium number of objects.Reference docsHugging Face transformers — SAM 3 and SAM 3 VideoThe integration this lesson's Build chapter uses: Sam3Processor / Sam3Model with post_process_instance_segmentation and the 1/0/-10 prompt-label convention; Sam3VideoModel / Sam3VideoProcessor with init_video_session, add_text_prompt, propagate_in_video_iterator and postprocess_outputs (object ids, scores, boxes, masks, prompt_to_obj_ids). Config values quoted in the lesson — 1008 px, 32 ViT layers, DETR 6 + 6 layers with 200 queries, 3 upsampling stages, 15-frame hotstart, reconditioning every 16 frames — come from here (transformers v5.17.0).Detection-only baselineYOLO-World: Real-Time Open-Vocabulary Object DetectionCheng et al., January 2024 · the boxes-at-high-fps option in the chooser: RepVL-PAN and region-text contrastive loss, 35.4 AP zero-shot on LVIS at 52.0 FPS on a V100 at 640² (19.2 ms per frame), no masks. The paper's fine-tuned variant also reports open-vocabulary instance segmentation, but the zero-shot tool is a detector.

Lesson text adapted from AI Engineering from Scratch (Phase 04, Lesson 24) and the Math Foundations Notebook reference build. The five labs — the prompt-mode comparator, the concept segmentation simulator, the memory tracker stepper, the open-vocabulary stack chooser and the latency ladder — are original to this page, as is the arithmetic they compute: the pass-count audit (1 vision encode + N concept passes; N detector passes + 1 encode + one mask decode per box in the cascade; C detector + ceil(O/16) tracker passes per frame with Object Multiplex), the memory bill (64 × 64 × 64 × 4 B = 1.05 MB per frame per object; 7 slots = 7.34 MB per object; 12 objects = 88 MB of separate banks), the RLE payload arithmetic (a 640 × 480 bus mask is 307,200 raw bytes, 961 runs and 5,765 characters — about 53× smaller — while a checkerboard costs roughly four characters per pixel, four times the raw bitmap), the click budget (~50 ms for the prompt encoder + mask decoder against a cached embedding, inside a 100 ms interactive budget), the SAM 2.1 frame-time ladder (11.0 / 11.8 / 15.6 / 25.3 ms from the published 91.2 / 84.8 / 64.1 / 39.5 FPS at 1024 px on an A100), the multiplex arithmetic (16 → 32 FPS on an H100 = 62.5 → 31.3 ms per frame), and the checkpoint sizes read from the Hugging Face file listings on 2026-09-16 (SAM ViT-H 641,090,864 parameters in a 2.56 GB file, i.e. the familiar 636M encoder and 2.4 GB in GiB; ViT-L 312,343,088 / 1.25 GB; ViT-B 93,735,728 / 0.37 GB; facebook/sam3 859,922,360 / 3.44 GB, gated). Every SAM 3 and 2026-model claim is presented as a dated snapshot with its official link, and the simulated scene's scores are labelled teaching values rather than benchmark results.