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.
Choose your stack
Four Ways to Build With SAM 3
Same model, different packaging. Pick by what you need and where it will run.
- 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:
Sam3ModelandSam3Processorfor text and box prompts, batching and cached embeddings; tracker and video classes too. - Ultralytics:
SAM3SemanticPredictorfor 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.
- 1Get accessRequest access to facebook/sam3 (and facebook/sam3.1) on Hugging Face.
- 2Create the environmentPython 3.12 and PyTorch with CUDA 12.6+.
- 3InstallClone facebookresearch/sam3 and pip install -e .
- 4AuthenticateRun hf auth login with your access token.
- 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 approvedOptional 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.
- Official repo: call
set_image()once, thenset_text_prompt()as often as you like on the same state. - Transformers: compute
get_vision_features()once and passvision_embeds; or cacheget_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.
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 endpoint | Returns | Typical price |
|---|---|---|
fal-ai/sam-3/image | Masks, optional overlay; up to 32 masks | $0.005 / request |
fal-ai/sam-3/image-rle | Run-length encoded masks | $0.005 / request |
fal-ai/sam-3/image/embed | Image embedding to reuse | $0.005 / request |
fal-ai/sam-3-1/image | SAM 3.1 masks; real-time WebSocket mode | See provider |
fal-ai/sam-3/video-rle | Tracked 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: 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.
- 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
Developer guides
Go Deeper
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.