Meta SAM 3 Playground

Developers · SAM 3 & SAM 3.1

Meta SAM for Developers Everything you need to build with SAM 3 and SAM 3.1: the four ways to run it, working image and video code, output formats, and how to take it to production.

segment.py
Animation of SAM 3 code producing masksA code editor fills in line by line: build the SAM 3 image model, set an image, send the text prompt “dog”. On the right, two dogs in a photo are then masked, each with a box and a confidence score. segment.py model = build_sam3_image_model()proc = Sam3Processor(model)state = proc.set_image(img)out = proc.set_text_prompt( state=state, prompt="dog")out["masks"], out["boxes"] ▶ run dog 0.94dog 0.91
Illustration: a few lines of Python return masks, boxes and scores.

Choose your stack

Four Ways to Build With SAM 3

Same model, different packaging. Pick by what you need and where it will run.

four routes
Animated diagram of four ways to build with SAM 3Your app sits at the top. Four routes light up in turn: the official sam3 repository, Hugging Face Transformers, Ultralytics, and a hosted API. The first three run on your GPU; the hosted API runs on the provider’s GPUs. your app Official repovideo · 3.1 · trainTransformersSam3ModelUltralyticsSAM 3 predictorsHosted APIfal · per request your GPU (CUDA 12.6+) provider GPU
Illustration of the four integration routes.
  • Official repo (facebookresearch/sam3): full feature set: images, video sessions, SAM 3.1 Object Multiplex, SAM 3 Agent and training code. Licence: SAM License.
  • Hugging Face Transformers: Sam3Model and Sam3Processor for text and box prompts, batching and cached embeddings; tracker and video classes too.
  • Ultralytics: SAM3SemanticPredictor for text and exemplars, SAM() for clicks and boxes; needs ultralytics 8.3.237+. Wrapper code is AGPL-3.0.
  • Hosted API: no GPU needed; pay per request or per frame batch.

Quickstart

Install and Run Locally

You need Python 3.12+, PyTorch 2.7+ and a CUDA 12.6+ GPU. Checkpoints are gated, so request access first.

  1. 1Get accessRequest access to facebook/sam3 (and facebook/sam3.1) on Hugging Face.
  2. 2Create the environmentPython 3.12 and PyTorch with CUDA 12.6+.
  3. 3InstallClone facebookresearch/sam3 and pip install -e .
  4. 4AuthenticateRun hf auth login with your access token.
  5. 5Run a promptBuild the image model, set an image and send a text prompt.
conda create -n sam3 python=3.12 && conda activate sam3
pip install torch==2.10.0 torchvision --index-url https://download.pytorch.org/whl/cu128
git clone https://github.com/facebookresearch/sam3.git && cd sam3
pip install -e .                    # add ".[notebooks]" or ".[train,dev]" as needed
hf auth login                       # after access to facebook/sam3 is approved

Optional speed-ups: Flash Attention 3 and the cc_torch package (see the repo README). Full walkthrough: install SAM 3 · Hugging Face access · system requirements

Image code

Segment an Image From Text

The same task, “find every yellow taxi”, in each local stack.

Official sam3 repo

from PIL import Image
from sam3.model_builder import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor

model = build_sam3_image_model()
processor = Sam3Processor(model)
state = processor.set_image(Image.open("street.jpg"))

out = processor.set_text_prompt(state=state, prompt="yellow taxi")
masks, boxes, scores = out["masks"], out["boxes"], out["scores"]

Hugging Face Transformers

import torch
from transformers import Sam3Model, Sam3Processor

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

inputs = processor(images=image, text="yellow taxi", return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

results = processor.post_process_instance_segmentation(
    outputs, threshold=0.5, mask_threshold=0.5,
    target_sizes=inputs.get("original_sizes").tolist())[0]

Ultralytics

from ultralytics.models.sam import SAM3SemanticPredictor

predictor = SAM3SemanticPredictor(overrides=dict(
    conf=0.25, task="segment", mode="predict",
    model="sam3.pt", quantize=16))   # or "sam3.1_multiplex.pt"

predictor.set_image("street.jpg")
results = predictor(text=["yellow taxi", "cyclist"])

Point and box prompts: Sam3TrackerModel in Transformers, or SAM("sam3.pt") with points/bboxes in Ultralytics. Step-by-step: Python tutorial

Key pattern

Encode Once, Prompt Many Times

The image encoder is the expensive part. Cache it and every extra prompt is cheap.

set_image once
Animation of encoding an image once and reusing it for many promptsA long bar shows the image encoder running once when set_image is called. Then three short bars show text prompts “dog”, “ball” and “person” each running quickly against the same cached image state. set_image(img) · runs once image encoder set_text_prompt(...) · cheap, repeat “dog”2 masks“ball”1 mask“person”3 masks illustrative timings · same idea in Transformers (vision_embeds) and Ultralytics (set_image)
Illustrative: encoder cost is paid once per image.
  • Official repo: call set_image() once, then set_text_prompt() as often as you like on the same state.
  • Transformers: compute get_vision_features() once and pass vision_embeds; or cache get_text_features() to run one prompt across many images.
  • Ultralytics: predictor.set_image() then call with a list of prompts.
  • Interactive apps: encode on upload, prompt on each click or keystroke.

Video code

Track Objects Through Video

Video uses a session: open the clip, add a prompt on any frame, read back masks with IDs.

video session
Animation of the SAM 3 video session flowFour stages light up in order: start_session loads the clip, add_prompt sends the text “player” on frame 0, propagation runs through every frame, and outputs return masks with object IDs per frame. start_sessionresource_pathadd_prompttext="player"propagateevery frameoutputsmasks + obj IDs JPEG folder or MP4 in · same IDs across frames out
Illustration of the request-based video API.
from sam3.model_builder import build_sam3_video_predictor

predictor = build_sam3_video_predictor()
sid = predictor.handle_request(request=dict(
    type="start_session", resource_path="match.mp4"))["session_id"]

resp = predictor.handle_request(request=dict(
    type="add_prompt", session_id=sid, frame_index=0, text="player"))
outputs = resp["outputs"]
  • Input: an MP4 or a folder of JPEG frames.
  • SAM 3.1: pull the latest repo code to load facebook/sam3.1; Object Multiplex makes many-object tracking much faster.
  • Guides: video segmentation · slow tracking

Hosted APIs

Use SAM 3 Without a GPU

Hosted providers run SAM 3 and SAM 3.1 for you. Example with fal’s Python client:

import fal_client      # pip install fal-client · set FAL_KEY

result = fal_client.subscribe(
    "fal-ai/sam-3-1/image",
    arguments={"image_url": "https://example.com/street.jpg"},
    # add prompt fields from the endpoint’s input schema
)
fal endpointReturnsTypical price
fal-ai/sam-3/imageMasks, optional overlay; up to 32 masks$0.005 / request
fal-ai/sam-3/image-rleRun-length encoded masks$0.005 / request
fal-ai/sam-3/image/embedImage embedding to reuse$0.005 / request
fal-ai/sam-3-1/imageSAM 3.1 masks; real-time WebSocket modeSee provider
fal-ai/sam-3/video-rleTracked video masks$0.005 / 16 frames

Prices change; check the provider before you budget. Comparison: SAM pricing guide · API guide: SAM 3 API

Outputs

What You Get Back

Every match comes back as a mask, a box and a confidence score.

masks · boxes · scores
Animated diagram of SAM 3 outputs and RLE encodingOne detected object produces three outputs: a binary mask, a bounding box and a score. Below, a row of mask pixels, ones and zeros, is compressed into run-length encoding: 4 ones, 4 zeros, 6 ones, 2 zeros. masks · H×W bool boxes · x0,y0,x1,y1 0.94scores · 0–1 → RLE [4, 4, 6, 2] compact, COCO-compatible
Illustration of SAM 3 outputs and RLE compression.
  • Masks: one binary (or probability) mask per object at image size.
  • Boxes: pixel coordinates (x0, y0, x1, y1).
  • Scores: 0–1 confidence; tune the threshold (0.25–0.5 is a common start).
  • Video: per-frame masks keyed by object ID.
  • Storage: use COCO RLE for compact masks, PNG for editing, polygons for labelling tools.

Details: mask formats · export masks

Performance

Performance Checklist

Speed

  • Cache image embeddings; batch images per prompt.
  • Use FP16/BF16 (Ultralytics quantize=16).
  • Install Flash Attention 3 where supported.
  • Use SAM 3.1 for videos with many objects.
  • Downscale very large frames, then upsample masks.

Quality

  • Short, concrete noun phrases beat sentences.
  • Add negative example boxes for look-alikes.
  • Raise the score threshold to cut false positives.
  • Correct drift in video with a click on the bad frame.
  • Fine-tune for niche domains with the repo’s training code.

Fixes: CUDA out of memory · empty masks · improve mask quality · fine-tuning

Production

Deploying SAM 3 in Production

Treat segmentation as an async GPU job, not a blocking web request.

request flow
Animated diagram of a production SAM 3 deploymentA request travels from the client to an API with a job queue, then to a GPU worker running SAM 3.1, which writes masks to storage. A dashed line returns a webhook or polling result to the client. Clientupload / URLAPI + queueauth · jobsGPU workerSAM 3.1Storagemasks · RLE webhook or poll → result URL
A common architecture; adapt it to your stack.
  • Queue jobs: video and large batches can take seconds to minutes.
  • Keep models warm: load the ~848M model once per worker, not per request.
  • Return URLs, not blobs: store RLE or PNG masks and send links.
  • Gate access: the checkpoint is gated; don’t expose raw weights.
  • Licence: pass on the SAM License terms when you distribute; check wrapper licences too. Summary: terms

Questions

Developer FAQ

What do I need to run SAM 3 locally?

Python 3.12+, PyTorch 2.7+ and an NVIDIA GPU with CUDA 12.6+. You also need approved access to the gated checkpoints on Hugging Face and an access token (hf auth login).

Should I use the official repo, Transformers or Ultralytics?

Use the official facebookresearch/sam3 repo for video tracking, SAM 3.1 and fine-tuning. Use Transformers if your stack is already Hugging Face. Use Ultralytics for a compact API and its export and tooling ecosystem, keeping its AGPL-3.0 licence in mind.

Is there a SAM 3 API?

Meta doesn’t run a public SAM 3 API, but hosted providers such as fal offer SAM 3 and SAM 3.1 endpoints for images, video, RLE masks and SAM 3D, billed per request or per frames.

How do I use SAM 3.1 in code?

Download the gated facebook/sam3.1 checkpoint, pull the latest sam3 repo code and reinstall it. Ultralytics can also load sam3.1_multiplex.pt in its SAM 3 image predictors.

Can I fine-tune SAM 3?

Yes. The official repo ships training and fine-tuning code; install it with pip install -e ".[train,dev]" and follow README_TRAIN.md.

Can I run SAM 3 without an NVIDIA GPU?

Only slowly. The Ultralytics wrapper can run image inference on CPU or Apple Silicon for testing, but for real workloads use a CUDA GPU or a hosted API.

Can I use SAM 3 in a commercial product?

Generally yes under the SAM License, which allows commercial use with restrictions on certain uses. Wrappers may add their own terms, such as Ultralytics’ AGPL-3.0. This is not legal advice.

Keep reading